std::basic_ios<CharT,Traits>:: good
|
bool
good
(
)
const
;
|
||
若流上的最近一次I/O操作成功完成则返回 true 。具体而言,返回 rdstate ( ) == 0 的结果。
请参阅 ios_base::iostate 了解设置流状态位的条件列表。
目录 |
参数
(无)
返回值
true 表示流错误标志位均为 false, false 则表示其他情况。
示例
#include <cstdlib> #include <fstream> #include <iostream> int main() { const char* fname = "/tmp/test.txt"; std::ofstream ofile{fname}; ofile << "10 " << "11 " << "12 " << "non-int"; ofile.close(); std::ifstream file{fname}; if (!file.good()) { std::cout << "#1. Opening file test.txt failed - " "one of the error flags is true\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for (int n; file >> n;) std::cout << n << ' '; std::cout << '\n'; if (file.bad()) { std::cout << "#2. I/O error while reading - badbit is true\n"; return EXIT_FAILURE; } else if (file.eof()) std::cout << "#3. End of file reached successfully - eofbit is true\n" "This is fine even though file.good() is false\n"; else if (file.fail()) std::cout << "#4. Non-integer data encountered - failbit is true\n"; }
可能的输出:
10 11 12 #4. Non-integer data encountered - failbit is true
参见
以下表格展示了所有可能的 ios_base::iostate 标志组合下, basic_ios 访问器( good() 、 fail() 等)的对应值:
| ios_base::iostate 标志位 |
basic_ios
访问器
|
|||||||
eofbit
|
failbit
|
badbit
|
good() | fail() | bad() | eof() | operator bool | operator! |
| false | false | false | true | false | false | false | true | false |
| false | false | true | false | true | true | false | false | true |
| false | true | false | false | true | false | false | false | true |
| false | true | true | false | true | true | false | false | true |
| true | false | false | false | false | false | true | true | false |
| true | false | true | false | true | true | true | false | true |
| true | true | false | false | true | false | true | false | true |
| true | true | true | false | true | true | true | false | true |