当我使用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。它可能会在未来造成恼人的错误。 –