In my program, I've redirected stdout to print to a file 'console.txt'. A function writes to that file like this:
void printToConsole(const std::string& text, const TCODColor& fc, const TCODColor& bc)
{
// write the string
cout << text << "@";
// write the two color values
cout << static_cast<int>(fc.r) << " "
<< static_cast<int>(fc.g) << " "
<< static_cast<int>(fc.b) << " "
<< static_cast<int>(bc.r) << " "
<< static_cast<int>(bc.g) << " "
<< static_cast<int>(bc.b) << " " << endl;
}
I have a function that reads from that file that looks like this:
void Console::readLogFile()
{
ifstream log("console.txt", ifstream::in);
if(!log.is_open())
{
cerr << "ERROR: console.txt not found!" << endl;
return;
}
// read new input into Console
string str;
while(getline(log, str))
{
cerr << "str: " << str << endl;
/* do stuff with str here */
}
cerr << endl;
log.close();
clearLogFile();
}
void Console::clearLogFile()
{
ofstream("console.txt", ios_base::trunc);
}
The first time through the readLogFile
, everything works fine. Afterwards, however, it starts to have problems. It will read in the first line of console.txt as a blank string. I stepped through the program with console.txt open in gvim, and monitored how it changed. The first time through, when it worked correctly, console.txt looks something like this:
1 moved UP.@191 191 191 0 0 0
2 Player moved.@191 191 191 0 0 0
~
~
which is as it should be. The program then goes to clearLogFile
, and afterwards console.txt is empty. However, the second time through, when I open the ifstream
, console.txt looks like this:
1 ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@moved UP.@191 191 191 0 0 0
2 Player moved.@191 191 191 0 0 0
~
~
This time, when getline
reads the first line into str
, str
is blank. Strangely, the cerr << "str: " << str << endl;
line still prints str
as "moved UP.@191 191 191 0 0 0", even though inspecting str
in gdb reveals that it's empty.
Anyone know what's going on here?