I wrote a list of code which try to read in digits from a text file. And I wanna stop the loop if up to the EOF of the file.
It comes to me a problem that .good() function doesn't work like what I thought. I wish I could get help from friends here :)
1 2 3 4 5 6 7 8 9
// To make it clear, I show here the core code
vector<int> arr;
int temp;
filein >> temp;
while (filein.good()){
arr.push_back(temp);
filein >> temp;
}
I can't read the last digit in my text file. But I substituted the while (filein.good()) with while (filein), the last digit be read.
And if I press Enter key at the end of the text file, .good() works as well.
The correct way to input data from C++ streams is to use the input operation as the condition.
Your code would then look like this:
1 2 3 4 5 6
vector<int> arr;
int temp;
while (filein >> temp){
arr.push_back(temp);
}
lays wrote:
I wanna know why .good() wrong. Thx.
It is wrong to use filein.good() as the condition because it checks the current state of the stream, but what you really wanted is to check if the input operation was successful.
For the same reason it is wrong to use filein itself as the condition (it still checks the current state of the stream).
// wrong method #1
while (filein.good()) // check: eofbit, failbit, badbit
{
// do input (what if it fails?)
}
// wrong method #2
while (filein) // check: failbit, badbit
{
// do input (what if it fails?)
}
// good method
while (/* do input */) // check: failbit, badbit right after input
{
// if the input fails above, the loop body won't be entered
}
if(filein) : true if the last input operation was successful ie. !filein.fail()
if( filein.good() ) : true if none of bad, fail, eof bits are set ie. filein.rdstate() == 0
After reading the last number (no newline at the end), the state is bad:false fail:false eof:true good:false if(filein) : true if( filein.good() ) : false