c++ - 如何清除输入行,而不仅仅是单个字符
问题描述
对不起,如果这是一个简单的问题,我是初学者。如果不是预期的类型,我希望能够从 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() 来实现这一点吗?提前致谢。
解决方案
如果您想坚持使用 cin,那么您将需要使用cin.ignore()忽略该行的其余部分
#include<limit>
...
double estimate;
do {
if(cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "The initial estimate was not a number" << endl;
}
cout << "Enter initial estimate of root: ";
cin >> estimate;
cout << endl;
} while(!cin);
Getline可能是更好的选择,因为它从由换行符 (\n) 分隔的输入流中获取一行。
do {
if(cin.fail()) {
cin.clear();
cout << "The initial estimate was not a number" << endl;
}
cout << "Enter initial estimate of root: ";
} while(!getline(cin, estimate);
推荐阅读
- database - 无法创建分片集合
- php - PHP和MySql,登录查询
- laravel - 在 cpanel 上上传项目时 laravel 错误
- javascript - ionic - `slot` 属性已被弃用 - eslint-plugin-vue
- typo3 - TYPO3 页面翻译不起作用。它在自由模式下显示错误,并且自定义元素未在 ConnectedMode 中翻译
- kubernetes - Kubernetes - Service Mesh 是必须的吗?
- python - 根据日期和以前的值填写缺失的数据
- python - Keras - val_accuracy 在 LSTM 模型中停留在 0.0000e+00
- android - 在没有互联网的情况下打开应用程序时如何使用毕加索加载缓存的图像
- reactjs - 如何将我的电子商务的订单 ID 与 React PayPal 联系起来