私のプログラムでは、stdoutをファイル「console.txt」に出力するようにリダイレクトしました。関数は次のようにそのファイルに書き込みます。
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;
}
そのファイルから次のような関数を読み取ります。
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);
}
初めてreadLogFile
、すべてが正常に動作します。しかし、その後、問題が発生し始めます。console.txtの最初の行に空白の文字列として読み込まれます。私はgvimでconsole.txtを開いた状態でプログラムをステップ実行し、プログラムがどのように変化するかを監視しました。初めて正常に機能したとき、console.txtは次のようになります。
1 moved UP.@191 191 191 0 0 0
2 Player moved.@191 191 191 0 0 0
~
~
あるべき姿です。その後、プログラムはに移動しclearLogFile
、その後、console.txtは空になります。ただし、2回目に開くとifstream
、console.txtは次のようになります。
1 ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@moved UP.@191 191 191 0 0 0
2 Player moved.@191 191 191 0 0 0
~
~
今回getline
は、最初の行をに読み込むstr
ときstr
は空白です。不思議なことに、 gdbで調べたところ空であることがわかったとしても、このcerr << "str: " << str << endl;
行はstr
「movedUP。@ 191 191 191 000」と表示されます。str
誰もがここで何が起こっているのか知っていますか?