Question

I have this code:

string a = "D:\\Users\\user-pc\\Desktop\\testing\\a.txt";

ifstream f;
    /*edit*/ string line;

    /*edit*/ getline(f, line);
f.open(a);
if ( f.eof() )
    cout << "ended";
else
    cout << "nope"

and the file 'a.txt' which has nothing in it.

the output is nope, alway nope. I don't get it.. Do I use it wrong?

EDIT: still .eof() not working

Was it helpful?

Solution

std::basic_istream<...>::eof() only returns true if a recent extraction set the appropriate bit in the stream state. When a file stream is constructed, its stream state is always that of std::ios_base::goodbit.

An alternative is to check if the next available character is the EOF character:

if (f.peek() == std::char_traits<char>::eof())

OTHER TIPS

eofbit error state flag is only set once a read tries to read past the end of the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top