如何清除输入行,而不仅仅是单个字符

How to clear line of input, not just single character

对不起,如果这是一个简单的问题,我是初学者。如果不是预期的类型,我希望能够清除来自 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() 来实现吗?提前致谢。

您可以将输入检索为字符串并解析它以检查它是否为数字:

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 从输入中检索双精度值。如果无法将值转换为双精度,它将 return false,或者 return true 并将结果存储到 out_value.

如果你想坚持使用 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);