Difference between ifstream.good () and bool (ifstream)

I am writing a program that takes several variables from a text file. When the program finds EOF,
it finishes entering data.

int main()
{
    int val, count = 0;
    ifstream fileIn;
    fileIn.open("num.txt");

    fileIn >> val;
    while (fileIn)
    {
        ++count;
        cout << "number: " << val << endl;
        fileIn >> val;
    }
    cout << "count: " << count << endl;

    fileIn.close();
    return 0;
}

num.txt file: 11 22 33 44

Program output:

number: 11
number: 22
number: 33
number: 44
count: 4

Everything is fine. But if I change the while status section from fileInto fileIn.good(), the
output of the program will look like this:

number: 11
number: 22
number: 33
count: 3

Now it skips the last value. Why is this happening and what is the difference between fileIn
and fileIn.good()?

+4
source share
2 answers

Now it skips the last value. Why is this happening and what is the difference between fileInand fileIn.good()?

fileIn >> val;
while (fileIn)
{
    ++count;
    cout << "number: " << val << endl;
    fileIn >> val;
}

"11 22 33 44" , fileIn. bool(fileIn) . , eof() . -.

, 44 val. , : count , val , fileIn >> val . while, .

fileIn.good() false, - state flags. , eof, fail bad

+4

if (fileIn) if (!fileIn.fail()), true, badbit failbit rdstate().

, fileIn.good() , rdstate() 0. , fail() eofbit.

. fileIn fileIn.good()?

val, while(fileIn.good()), , , fileIn eofbit. if(infs), .

+2

Source: https://habr.com/ru/post/1668206/


All Articles