ios::good() problem

I'm calling ios::good() in my code as follows:

fstream read_trace;
string line;
vector<string> lines;
read_trace.open("tracecomepare.txt");

cout<<"state of thingy is "<<read_trace.good()<<endl;


while(read_trace.good())
{
getline(read_trace,line);
lines.push_back(line);
cout<<"line read"<<endl;
}

but it's returning as 0, untrue, rather than 1/true. I don't understand why this is? Can anyone help me understand?
Is it possible that your program failed to open the file tracecomepare.txt [sic]?

-Albatross
It probably couldn't find the file, so opening failed. Make sure the file is in the current directory (if launching from an IDE, this is often the project directory and not necessarily the same directory the exe is in).
Thanks Disch! :)
Note that after you get the file to open, that input loop will run past the end of file and produce one extra line of output and one extra item in the vector "lines" (specifically, an empty string), because it does not check the status of the stream after reading from it.

The typical C++ input loop is

1
2
3
4
5
while(getline(read_trace,line))
{
    lines.push_back(line);
    cout<<"line read"<<endl;
}

Last edited on
Topic archived. No new replies allowed.