c语言如何让程序回到开头,如何将ifstream返回到刚刚在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(),这就是为什么它似乎没有改变(因为它确实没有).谢谢大家的贡献.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值