C++ good() eof() fail() 那点事
while(!infile.fail())
{
infile>>number;
cout<<number<<endl;
count++;
}
这段代码正确吗,答案:错误。看了好久才发现问题在哪。 原来fail()是不考虑文件结尾的。如果执行这段代码,假设输入流为12 23 34 56,那么输出的结果为
12
23
34
56
56
也就是说当文件已经到结尾时,infile.fail()仍未false,即文件仍没错误。此处该用eof()。
| iostate value (member constant) | indicates | functions to check state flags | ||||
|---|---|---|---|---|---|---|
| good() | eof() | fail() | bad() | rdstate() | ||
| goodbit | No errors (zero value iostate) | true |
false |
false |
false |
goodbit |
| eofbit | End-of-File reached on input operation | false |
true |
false |
false |
eofbit |
| failbit | Logical error on i/o operation | false |
false |
true |
false |
failbit |
| badbit | Read/writing error on i/o operation | false |
false |
true |
true |
badbit |
浙公网安备 33010602011771号