문제

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

도움이 되었습니까?

해결책

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())

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top