ifstream,行尾并移至下一行?
如何使用 std::ifstream 检测并移动到下一行?
void readData(ifstream& in)
{
string sz;
getline(in, sz);
cout << sz <<endl;
int v;
for(int i=0; in.good(); i++)
{
in >> v;
if (in.good())
cout << v << " ";
}
in.seekg(0, ios::beg);
sz.clear();
getline(in, sz);
cout << sz <<endl; //no longer reads
}
我知道如果发生错误,好的会告诉我,但一旦发生错误,流就不再工作。 在读取另一个 int 之前,如何检查我是否位于行尾?
how do i detect and move to the next line using std::ifstream?
void readData(ifstream& in)
{
string sz;
getline(in, sz);
cout << sz <<endl;
int v;
for(int i=0; in.good(); i++)
{
in >> v;
if (in.good())
cout << v << " ";
}
in.seekg(0, ios::beg);
sz.clear();
getline(in, sz);
cout << sz <<endl; //no longer reads
}
I know good would tell me if an error happened but the stream no longer works once that happens. How can i check to see if i am at the end of line before reading another int?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在循环后使用
in.clear();
清除流的错误状态,然后流将再次工作,就好像没有发生错误一样。您还可以将循环简化为:
如果操作成功,则流提取将返回,因此您可以直接测试它,而无需显式检查
in.good();
。You should clear the error state of the stream with
in.clear();
after the loop, then the stream will work again as if no error happened.You might also simplify your loop to:
The stream extraction returns if the operation succeeded, so you can test this directly without explicitly checking
in.good();
.使用ignore() 忽略所有内容,直到下一行:
如果您必须手动执行此操作,只需检查其他字符以查看是否为'\n'
这可能会失败,因为您在清除坏位之前进行了查找。
Use ignore() to ignore everything until the next line:
If you must do it manually just check othe character to see if is '\n'
This is probably failing because you are doing a seek before clearing the bad bits.