很抱歉,如果这是一个简单的问题,我是初学者。如果不是期望的类型,我希望能够从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()实现吗?预先感谢。
答案 0 :(得分:1)
如果您想坚持使用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);
答案 1 :(得分:0)
您可以将输入作为字符串检索,并解析它是否为数字:
bool convert_string_to_double(const std::string &str, double &out_value){
try{
out_value = stod(str);
return true;
} catch (const std::invalid_argument &e) {
return false;
}
}
bool get_double_from_input(double &out_value){
std::string input_str;
cin >> input_str;
return convert_string_to_double(input_str, out_value);
}
然后使用get_double_from_input
从输入中检索双精度值。如果无法将值转换为双精度,它将返回false
,或者返回true
并将结果存储到out_value
中。