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

问题描述 投票:0回答:2

我很抱歉,如果这是一个简单的问题,我是一个初学者。我希望能够从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:在我的代码目前,非发基金不断阅读,所以我得到:

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++ get cin getline
2个回答
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);

0
投票

你可以retreive输入string和解析它,以检查它是否是一个数字:

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

然后使用qazxsw POI从输入检索双重价值。如果无法转换值加倍,或返回get_double_from_input,结果存储到false它将返回qazxsw POI。

© www.soinside.com 2019 - 2024. All rights reserved.