C ++检查整个输入是否为浮点数

时间:2014-03-28 00:20:28

标签: c++ validation input

所以我正在尝试检查我的输入是否有效输入1或2.当我输入3/4/5/6或任何字符时它会起作用。但是一旦我在输入中的任何地方输入1或2个字符,它会直接跳过检查并继续使用代码。

因此,当我输入1a时,它会选择案例1并将a保留在输入缓冲区中并弄乱我的代码......

另外,我想对其他只有浮点数的输入进行检查,这些输入可以是关于所有内容的,所以我不想只检查1 || 2

do
{
    while(!(cin >> iChoiceFile))
    {
        cout << "ERROR: Please enter 1 or 2: ";
        cin >> iChoiceFile;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    switch(iChoiceFile)
    {
        case 1: makeNewFile();
            valid_answer = true;
            break;

        case 2: valid_answer = true;
            break;

        default: cout << "ERROR: Please enter 1 or 2: ";
            valid_answer = false;
            break;
    }

}while(!valid_answer);

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来你真正想要的是检查12的输入为整数,而不是浮点数。

请改为尝试:

#include <cctype>
#include <cstdlib>

//...

string choice;
cout << "Enter a character: ";
getline(cin,choice);
while(!isdigit(choice[0]) || (choice[0] != '1' && choice[0] != '2')){
    cout << "\nERROR! Please enter 1 or 2 only!" << endl;
    cout << "Enter a character: ";
    getline(cin,choice);
}
switch (atoi(&choice[0])){
    case 1: 
        makeNewFile();
        break;

    case 2:
        cout << "Functionality to execute when input is a 2" << endl;
        break;
}//no need for 'default'

示例执行:

  

输入一个字符:5
  错误!请输入1或2!
  输入一个字符:a   错误!请输入1或2!
  输入一个字符:这是一个完整的怪字符串
  错误!请输入1或2!
  输入一个字符:1s
  makeNewFile();

我们在最后一种情况下成功忽略了1之后的所有字符。