繁体   English   中英

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

[英]How do I return an ifstream back to the beginning of a line that was just read in C++?

在我使用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
} 

因此,如果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
}

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

更新#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
}

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

将fstream位置存储在文件中(查看文档)。

读线。

如果情况发生 - 转到文件中的存储位置。

你需要这个:

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

但是,经常调用搜索功能是相当昂贵的,即我会考虑删除再次读取行的要求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM