简体   繁体   English

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

[英]C++ Check if entire input is a float

So I'm trying to check my input for a valid input of 1 or 2. It works when I just enter a 3/4/5/6 or any character. 因此,我尝试检查输入的有效输入是1还是2。当我输入3/4/5/6或任何字符时,它可以工作。 But once I enter 1 or 2 anywhere in the input with some characters it skips straight through the check and continues on with the code. 但是,一旦我在输入中的任意位置输入1或2并加上一些字符,它将直接跳过检查并继续执行代码。

So when I for example enter 1a, it chooses case 1 and keeps the a in the input buffer and messes up my code... 因此,例如当我输入1a时,它将选择情况1并将a保留在输入缓冲区中并弄乱了我的代码...

Also I want to run a check on other float-only inputs that can be about everything so I don't just want to check for 1 || 另外,我想对其他所有仅用于浮点数的输入进行检查,因此我不仅要检查1 ||。 2 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);

Thanks in advance! 提前致谢!

It looks like what you actually want is to check for an input for 1 or 2 as integers, not floats. 看起来您实际想要的是检查12的输入是否为整数,而不是浮点数。

Try this instead: 尝试以下方法:

#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'

Sample execution: 示例执行:

Enter a character: 5 输入字符:5
ERROR! 错误! Please enter 1 or 2 only! 请仅输入1或2!
Enter a character: a 输入一个字符:
ERROR! 错误! Please enter 1 or 2 only! 请仅输入1或2!
Enter a character: This is an entire weird string 输入一个字符:这是一个完整的怪异字符串
ERROR! 错误! Please enter 1 or 2 only! 请仅输入1或2!
Enter a character: 1s 输入字符:1s
makeNewFile(); makeNewFile();

We've successfully ignored all the characters after 1 in the last case. 在最后一种情况下,我们已成功忽略了1之后的所有字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM