簡體   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