首页 > 解决方案 > 如何清除输入行,而不仅仅是单个字符

问题描述

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

标签: c++getcingetline

解决方案


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

推荐阅读