Sunday, March 8, 2009

How to use "eof()" in c++ file operation

Today I find a interesting problem when I read data from text file.
The code like this:
[code]
vector data;
ofstream os;
os.open("filename");
while(!os.eof())
{
int a;
os>>a;
data.push_back(a);
}
[/code]


After I run this simple program, a problem is there :
The size of vector data is longer 1 than the size of data in the filename.

What's wrong with this program?

I find it because eof is to check error information that when you read data from file.
if "os>>a" is wrong, program still will add a to the vector.
So How to fix that:

[code]

vector data;
ofstream os;
os.open("filename");
int a;
while(os>>a)
{

data.push_back(a);
}
[/code]

No comments: