这是来自加速 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之前和之后)不是更安全吗?