今天,我们的数据结构课程要求我们实施霍纳法则。我终于做到了,但是有一个小错误让我非常不高兴。我使用while
循环读取和保存多项式的系数,并使用另一个cin
读取变量x
的值。问题是,当我到达EOF以终止读取系数之后,读取变量cin
的以下x
部分将不执行。这让我很困惑。
while(std::cin>>n){
coeff.append(n);
}
std::cout<<"Now enter the value";
std::cin>>x;
该程序语法正确,但是只跳过读取变量cin
的第二个x
。
最简单的方法是要求所有系数都在一行上输入:
std::string line;
if (std::getline(std::cin, line))
{
std::istringstream is(line);
int n = 0; // or whatever type you're using.
while (is >> n)
{
coeff.append(n);
}
std::cout << "Enter the value: ";
std::cin >> x;
// Evaluation code here.
}
else
{
// Possibly handle error
}
[其他选项包括将“魔术”系数定义为标记,或者接受一些无效(即非数字)输入,然后在继续之前先输入clear()
流。