C++ ifstream 读到末尾后 seekg不起作用的问题

dixuexiongyingss 2015-04-18 05:19:18

string strBuf;
ifstream is("1.txt", ios::in); // 1.txt存在
if (!is)
{
return -1;
}

while (is >> strBuf) // 一直读文件直到文件末尾
{
cout << strBuf << endl;
}

is.seekg(0, ios::beg); //设置文件读指针到开头
while (is >> strBuf) //继续读,这时好像读不了了。
{
cout << strBuf << endl;
}


如上所述,在seekg后读文件就没有内容了,请高手解答
...全文
498 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
michael2988 2015-04-22
  • 打赏
  • 举报
回复
C++98 If the eofbit flag is set before the call, the function fails (sets failbit and returns). 读完一次要clear掉

    is.clear();
    is.seekg(0, std::ios::beg);
幻夢之葉 2015-04-22
  • 打赏
  • 举报
回复
C++ IO流有几个标志位 failbit // 一般错误,如要求输入int却输入字符串 badbit // 更底层的错误,一般是致命性的 eofbit // 流结尾标志 goodbit // 流无错误的标志,如上述三个有一个被置位,这个都是false 你文件结尾了,eofbit被置位,说明流到达结尾! 然后流的状态就是失败的 你需要重置 is.setstate (ios::eofbit); 或者 is.clear(); 来再次使用流
dixuexiongyingss 2015-04-19
  • 打赏
  • 举报
回复
引用 3 楼 zxh707wk 的回复:
[quote=引用 2 楼 jiht594 的回复:] C++98 If the eofbit flag is set before the call, the function fails (sets failbit and returns).
c也有这样一段话[/quote] 你们在那看到的呢,我在官方文档上没有看到这个说明呢
缄默笔记 2015-04-19
  • 打赏
  • 举报
回复
is.clear();
is.seekg(ios::beg); //回到文件开始
707wk 2015-04-19
  • 打赏
  • 举报
回复
老谭的书
引用 6 楼 dixuexiongyingss 的回复:
你们在那看到的呢,我在官方文档上没有看到这个说明呢
dixuexiongyingss 2015-04-18
  • 打赏
  • 举报
回复
引用 2 楼 jiht594 的回复:
C++98 If the eofbit flag is set before the call, the function fails (sets failbit and returns).
大概明白了 是说seekg()函数 是吧,那意思就是说 文件读到末尾后,就无法再重新读了,只能重新打开再次读喽!
dixuexiongyingss 2015-04-18
  • 打赏
  • 举报
回复
引用 2 楼 jiht594 的回复:
C++98 If the eofbit flag is set before the call, the function fails (sets failbit and returns).
怎么解释呢,我英文有点水
707wk 2015-04-18
  • 打赏
  • 举报
回复
引用 2 楼 jiht594 的回复:
C++98 If the eofbit flag is set before the call, the function fails (sets failbit and returns).
c也有这样一段话
jiht594 2015-04-18
  • 打赏
  • 举报
回复
C++98 If the eofbit flag is set before the call, the function fails (sets failbit and returns).
jiht594 2015-04-18
  • 打赏
  • 举报
回复
再读之前 is.clear(); 试试

65,210

社区成员

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

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