【发布时间】:2019-06-28 17:32:32
【问题描述】:
对不起,如果这是一个简单的问题,我是初学者。如果不是预期的类型,我希望能够从 cin 清除输入。我让它适用于单个字符或值,但是当我在行上输入多个字符时会出现问题。
例如,提示用户输入双精度数。如果它不是双重的,我会收到一条错误消息并重新提示。如果我输入更长的字符串,也会出现这种情况。
EX 1:预期输出
Enter initial estimate: a
The initial estimate is not a number.
Enter initial estimate: afdf
The initial estimate is not a number.
EX 2:在我目前的代码中,afdf 被不断读取,所以我得到:
Enter initial estimate of root : a
The initial estimate was not a number
Enter initial estimate of root : afdf
The initial estimate was not a number
Enter initial estimate of root :
The initial estimate was not a number
Enter initial estimate of root :
The initial estimate was not a number
Enter increment for estimate of root :
The increment was not a number
我尝试过使用 cin.clear() 和 cin.get() 以及查看 getline() 但这不起作用。
while (numTries < 4)
{
numTries++;
cout << "Enter initial estimate of root : ";
cin >> estimate;
if (!(cin.fail()))
{
if ((estimate >= minEst) && (estimate <= maxEst))
{
break;
}
else
{
if (numTries == 4)
{
cout << "ERROR: Exceeded max number of tries entering data" << endl;
return 0;
}
cout << "" << endl;
cout << "Value you entered was not in range\n";
cout << fixed << setprecision(3) << minEst << " <= initial estimate <= " << maxEst << endl;
}
}
else
{
cout << "\nThe initial estimate was not a number\n";
cin.clear();
cin.get();
}
}
如何确保在下次输入时清除输入?我可以使用 getline() 来实现这一点吗?提前致谢。
【问题讨论】: