當我使用ifstream從文件中讀取一行後,是否有辦法讓流回到我剛剛讀取的行的開頭,有條件?如何將ifstream返回到剛剛用C++讀取的行的開頭?
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(),這就是爲什麼它沒有任何改變(因爲它沒有改變)。謝謝大家的貢獻。
使用tellg()在讀取該行之前獲取流位置並seekg()將流位置設置爲之前保存的位置。 –
順便說一下,ifs >>到字符串不是獲取行,而是字。使用std :: getline –
感謝您關注getline。它可能會在未來造成惱人的錯誤。 –