关于eof()和fail()的问题

SJ2050 2018-03-31 09:20:36
#include <iostream>
#include<sstream>
#include <string>

using namespace std;

int main()
{
char c;
string a{ "abc" };
istringstream in(a);

while (1)
{
if (in.eof()) break;

in >> c;
cout << c << " ";
}
system("pause");
return 0;
}

#include <iostream>
#include<sstream>
#include <string>

using namespace std;

int main()
{
char c;
string a{ "abc" };
istringstream in(a);

while (1)
{
if (in.peek() == ' ') in.ignore(1024, ' ');
if (in.eof()) break;

in >> c;
cout << c << " ";
}
system("pause");
return 0;
}

#include <iostream>
#include<sstream>
#include <string>

using namespace std;

int main()
{
char c;
string a{ "abc" };
istringstream in(a);

while (1)
{
if (in.peek() == ' ') in.ignore(1024, ' ');
if (in.fail()) break;

in >> c;
cout << c << " ";
}
system("pause");
return 0;
}


第二个程序输出正常,第一和第三个最后的c输出了两次,我有两个疑惑:
1.为什么peek后eof就返回TRUE了,peek不是不取走的吗
2.当达到流结尾时,eof位被设置,不是也会导致failbit位被设置,为什么当eof时,fail还不返回true
...全文
309 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
这是什么语法: string a{ "abc" }; ? 为什么不是 string a("abc");
  • 打赏
  • 举报
回复
将 if (in.peek() == ' ') in.ignore(1024, ' '); 修改为 in.peek(); 看起来也不会改变程序输出,楼主可以试试。
  • 打赏
  • 举报
回复
然后关于第2个和第3个,in.ignore(1024, ' '); 应该省略也没关系。 起作用的是peek(), 输入序列没有更多字符可读,则设置internal state flag为eofbit,对应eofbit, eof() 和 fail() 分别返回 true 和 false,第2个例子正确退出。 第3个例子:第 4 次 loop 输出 'c', 因为没有字符可读,state flag 也会设置 failbit,fail() 因此将返回true,第5次loop 时执行break。 希望我说的没错,你可以用in.rdstate() 看一下有设哪些flag。 http://www.cplusplus.com/reference/ios/ios/fail/ http://www.cplusplus.com/reference/ios/ios/eof/ http://www.cplusplus.com/reference/istream/istream/peek/
  • 打赏
  • 举报
回复
关于第 1 个例子你看下这个, https://stackoverflow.com/questions/1494342/end-of-file-in-c 就是当读失败之后才设为true,所以第 1 个例子,第4次读之后eof才设为true,第4次读,char c 保持为“c”,没变过,所以多输出一次 a b c c。 EOF is true when you try and read past the EOF. Reading upto the end of file does not change the state. So EOF becomes true when you read the first value that does not exist past the end of file. – Martin York Sep 29 '09 at 19:18 eof 输出: 0 a 0 b 0 c 0 c 1
SJ2050 2018-03-31
  • 打赏
  • 举报
回复
新的编译器支持的

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧