# 如何清除输入的线，而不仅仅是单个字符

##### 问题描述投票：0回答：2

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：在我的代码目前，非发基金不断阅读，所以我得到：

``````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
``````

`````` 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();
}
}
``````

c++ get cin getline
##### 2个回答
1

``````#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);
``````

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);
}
``````