gpt4 book ai didi

c++ - 为什么 istream::get 将 failbit 和 eofbit 设置在一起?

转载 作者:行者123 更新时间:2023-11-30 03:53:14 28 4
gpt4 key购买 nike

我想知道为什么 istream::get 将 failbit 和 eofbit 设置在一起。

std::getline 的行为不同:它在遇到文件末尾时设置 eofbit,在您尝试读取文件末尾时设置 failbit。所以你可以这样写:

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;
}

但这听起来不对...

最佳答案

不幸的是,使用 istream::get 制作一个 getline 函数将导致该函数内部出现一些笨拙的代码,因为根据规范,它同时设置了 eofbitfailbit 当它到达文件末尾时。标准 istream::getline 解决此问题的方法是使用 istreamrdbuf() 来检查值。看起来这可能是解决这个问题的唯一方法(除了操纵流的故障状态之外)

关于c++ - 为什么 istream::get 将 failbit 和 eofbit 设置在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201447/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com