何时何地清除c++中的输入流

When and where to clear input stream in c++

本文关键字:输入流 c++ 清除 何时何地      更新时间:2023-10-16

以下是加速c++中的一个示例:

// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
       // get rid of previous contents
       hw.clear();
       // read homework grades
       double x;
       while (in >> x)
          hw.push_back(x);
       // clear the stream so that input will work for the next student
       in.clear();
    }
    return in;
}

in.clear()行应该清除以前输入可能产生的错误,但为什么在我们开始输入之前,即while (in >> x)行之前,它没有被清除?事实上,两次清除输入流(在输入hw之前和之后)不是更安全吗?

您在到达流的末尾后清除标志,因为您打算到达流的末端。由另一个函数引发的标志可能不是有意的,可能需要处理。