gpt4 book ai didi

c++ - ifstream.good() 和 bool(ifstream) 的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:36 29 4
gpt4 key购买 nike

我正在编写一个程序,它从一个文本文件中获取多个变量。当程序发现EOF时,
它结束输入数据。

int main()
{
int val, count = 0;
ifstream fileIn;
fileIn.open("num.txt");

fileIn >> val;
while (fileIn)
{
++count;
cout << "number: " << val << endl;
fileIn >> val;
}
cout << "count: " << count << endl;

fileIn.close();
return 0;
}

num.txt 文件:11 22 33 44

程序输出:

number: 11
number: 22
number: 33
number: 44
count: 4

一切正常。但是,如果我将 while 条件部分从 fileIn 更改为 fileIn.good()
程序输出将如下所示:

number: 11
number: 22
number: 33
count: 3

它现在跳过最后一个值。为什么会发生这种情况,fileIn
之间有什么区别和 fileIn.good()?

最佳答案

It skips last value now. Why is this happening and what's the difference between fileIn and fileIn.good()?

fileIn >> val;
while (fileIn)
{
++count;
cout << "number: " << val << endl;
fileIn >> val;
}

对于与 fileIn 关联的流中的给定内容 "11 22 33 44"。使用 bool(fileIn) conversion operator将返回流是否没有失败。注意到达eof()不是流的失败。失败基本上是指 I/O 操作失败。

因此,在将最后一个数字 44 读入 val 之后。再次进入循环,因为流没有失败:count 递增,val 被打印,但是下一个 fileIn >> val 会失败.然后将在 while 循环的条件下对其进行测试,失败将导致循环退出。

正在做 fileIn.good()如果任何流的 state flags 返回 false已设置。具体来说,eof , failbad

关于c++ - ifstream.good() 和 bool(ifstream) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926303/

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