C++ getline 后返回到文件开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5343173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:56:53  来源:igfitidea点击:

Returning to beginning of file after getline

c++

提问by bq54

So i've read all the lines from a file thusly

所以我已经从文件中读取了所有行

while (getline(ifile,line))
    {
        // logic
    }

Where ifile is an ifstream and line is a string

其中 ifile 是一个 ifstream 而 line 是一个字符串

My problem is I now want to use getline over again, and seem to be unable to return to the beginning of the file, as running

我的问题是我现在想再次使用getline,并且似乎无法返回到文件的开头,因为正在运行

cout << getline(ifile,line);

Will return 0

将返回 0

I've attempted to use:

我尝试使用:

ifile.seekg (0, ios::beg);

To no avail, it seems to have no effect. How do I go back to the start of the file?

无济于事,似乎没有效果。我如何回到文件的开头?

回答by Konrad Rudolph

As of C++11, your seekgworks as expected, and you don't need to change anything.

从 C++11 开始,seekg按预期工作,无需更改任何内容。

Before C++11:

在 C++11 之前:

Since you have reached the end of the file, the eofflag will be set. You need to clear that using ifile.clearthentry seeking:

由于您已到达文件末尾,因此eof将设置标志。您需要清除使用ifile.clear然后尝试寻找:

ifile.clear();
ifile.seekg(0, ios::beg);

回答by Angus Comber

This is because the eof flag has been set on the stream - due to you reaching the end of the file. so you have to clear this as an additional step.

这是因为已经在流上设置了 eof 标志 - 由于您到达了文件的末尾。所以你必须清除它作为一个额外的步骤。

Eg

例如

ifile.clear();
ifile.seekg (0, ios::beg);

回答by iko79

FYI: In my case, the order DID matter, thus

仅供参考:就我而言,订单确实很重要,因此

  1. clear
  2. seek
  1. 清除
  2. 寻找

otherwise the next getline operation failed (MSVC v120)

否则下一个 getline 操作失败 (MSVC v120)