C++ ifstream,行尾并移动到下一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/477408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:33:02  来源:igfitidea点击:

ifstream, end of line and move to next line?

c++stdifstream

提问by Martin York

how do i detect and move to the next line using std::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
}

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?

我知道好会告诉我是否发生错误,但一旦发生错误,流就不再有效。在读取另一个 int 之前,如何检查我是否在行尾?

回答by Martin York

Use ignore() to ignore everything until the next line:

使用 ignore() 忽略所有内容,直到下一行:

 in.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

If you must do it manually just check othe character to see if is '\n'

如果您必须手动执行此操作,只需检查其他字符以查看是否为 '\n'

char next;
while(in.get(next))
{
    if (next == '\n')  // If the file has been opened in
    {    break;        // text mode then it will correctly decode the
    }                  // platform specific EOL marker into '\n'
}
// This is reached on a newline or EOF

This is probably failing because you are doing a seek before clearing the bad bits.

这可能会失败,因为您在清除坏位之前进行了搜索。

in.seekg(0, ios::beg);    // If bad bits. Is this not ignored ?
                          // So this is not moving the file position.
sz.clear();
getline(in, sz);
cout << sz <<endl; //no longer reads

回答by sth

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.

您应该in.clear();在循环之后清除流的错误状态,然后流将再次工作,就好像没有发生错误一样。

You might also simplify your loop to:

您还可以将循环简化为:

while (in >> v) {
  cout << v << " ";
}
in.clear();

The stream extraction returns if the operation succeeded, so you can test this directly without explicitly checking in.good();.

如果操作成功,流提取将返回,因此您可以直接对此进行测试,而无需显式检查in.good();