如何将ifstream返回到刚刚在C++中读取的行的开头?

Kim*_*y W 6 c++ file ifstream

在我使用ifstream从文件中读取一行之后,有没有办法将流重新带回到我刚读过的行的开头?

using namespace std;
//Some code here
ifstream ifs(filename);
string line;
while(ifs >> line)
{
   //Some code here related to the line I just read

   if(someCondition == true)
   {
    //Go back to the beginning of the line just read
   }
   //More code here
} 
Run Code Online (Sandbox Code Playgroud)

因此,如果someCondition为true,则在下一个while循环迭代期间读取的下一行将是我刚才读到的同一行.否则,下一个while循环迭代将在文件中使用以下行.如果您需要进一步澄清,请不要犹豫.提前致谢!

更新#1

所以我尝试了以下方法:

while(ifs >> line)
{
   //Some code here related to the line I just read
   int place = ifs.tellg();
   if(someCondition == true)
   {
    //Go back to the beginning of the line just read
    ifs.seekg(place);
   }
   //More code here
}
Run Code Online (Sandbox Code Playgroud)

但是当条件为真时,它不再读同一行.整数是一个可接受的类型吗?

更新#2:解决方案

我的逻辑出错了.这是修正后的版本,我希望它适用于任何好奇的版本:

int place = 0;
while(ifs >> line)
{
   //Some code here related to the line I just read

   if(someCondition == true)
   {
    //Go back to the beginning of the line just read
    ifs.seekg(place);
   }
  place = ifs.tellg();
   //More code here
}
Run Code Online (Sandbox Code Playgroud)

对tellg()的调用已移至最后,因为您需要寻找先前读取行的开头.我第一次调用tellg()然后在流改变之前调用seekg(),这就是为什么它似乎没有改变(因为它确实没有).谢谢大家的贡献.

Die*_*ühl 6

没有直接的方法可以说“回到最后一行的开头”。但是,您可以使用 返回到您保持的位置std::istream::tellg()。也就是说,在阅读您将使用的一行之前tellg(),然后seekg()返回到该位置。

然而,频繁调用搜索函数是相当昂贵的,也就是说,我会考虑取消再次读取行的要求。