Tuesday, November 14, 2006

C++ note: be careful with ifstream

The following is the correct and actually standard way of reading something

while(file.good())
{
file >> s;
cout << s;
}

However, the following is wrong:

while(file.good())
{
file.get(t);
cout << t ;
}

it will normally repeat the last char in the file. The reason is that file.good only changes after get() is called. This is the way

while(file.get(t))
{
cout << t ;
}

file.get(t) will return success if the process works.

No comments: