在我使用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(),这就是为什么它似乎没有改变(因为它确实没有).谢谢大家的贡献.