【发布时间】:2015-05-12 21:08:48
【问题描述】:
我想知道为什么 istream::get 将 failbit 和 eofbit 设置在一起。
std::getline 的行为不同:它在遇到文件末尾时设置 eofbit,当您尝试读取文件末尾时设置失败位。所以你可以写:
while (std::getline(is, s) {
blablabla... // gets executed once after end of file has been reached
}
而如果您使用 std::get 定义自己的 getSthg 函数
std::istream& myOwnGetLine(std::istream& is, std::string& s) {
char c;
while (is.get(c)) {
blablabla...
}
return is;
}
然后:
while (myOwnGetLine(is, s)) { // fails if eof has been reached
blablabla // won't get executed for the last line of the stream
}
那么:我做错了什么?我想出的解决方法是:
std::istream& myOwnGetLine(std::istream& is, std::string& s) {
*if (is.rdstate() & std::ios::eofbit) {
is.clear(std::ios::failbit);
return is;
}*
char c;
while (is.get(c)) {
blablabla...
}
*if (is.rdstate() & std::ios::eofbit) {
is.clear(std::ios::eofbit);
}*
return is;
}
但这听起来不对……
【问题讨论】: