【问题标题】:ifstream, end of line and move to next line?ifstream,行尾并移至下一行?
【发布时间】:2010-10-03 09:46:29
【问题描述】:

如何使用 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
}

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

【问题讨论】:

    标签: c++ std ifstream


    【解决方案1】:

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

     in.ignore(std::numeric_limits<std::streamsize>::max(), '\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
    

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

    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
    

    【讨论】:

      【解决方案2】:

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

      您还可以将循环简化为:

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

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

      【讨论】:

      • 有效的 int 可以紧跟在文件末尾。要将其视为成功,您需要检查 in.fail() 是否为 false,因为即使提取操作成功,如果到达文件末尾, in.good() 也会返回 false。
      • @Charles:隐含的operator void* 调用fail,所以while (in &gt;&gt; v) 将在提取成功时成功,无论EOF 状态如何。
      • @dalle,是的,我知道,这就是使 while 循环“按预期”工作的原因。我只是在评论,因为某事将明确检查 'in.good()' 与使用 'while (in >>v)' 习语进行了比较,并想指出它们不等价。
      猜你喜欢
      • 1970-01-01
      • 2014-07-10
      • 2011-10-14
      • 2023-01-26
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多