C++ 如何防止无效输入?

C++ How to protect against invalid input?

在我的程序中,我希望用户在两个选项中进行选择。简单地说,1 或 2。我已将程序编写到可以防止无效数值(如 3 或 28)的位置,但我无法防止字母输入。

代码如下:

int whileInt = 0;
int choiceOne_One = 0;
while(whileInt == 0)
{
    cin >> choiceOne_One;

    if(choiceOne_One != 1 && choiceOne_One != 2)
    {
        cout << "Woah! That wasn't an option! Try Again.\n";
    }
    else if(choiceOne_One == 1)
    {
        whileInt++;
        cout << "\nYou have died. Be more careful.\n";
    }
    else if(choiceOne_One == 2)
    {
        whileInt++;
        cout << "\nYou have survived the alien invasion due to your cunning sense of "
            "safety.\nCongratulations.\n";
    }
}

我的大脑还在Java,请帮我解决这个问题。它一定会受到赞赏。

尝试用 std::getline 读取 std::string,然后简单地将字符串与“1”或“2”进行比较。否则,您可以只使用 std::getline 读取整行,然后使用 std::stoi (C++11) 将读取的字符串转换为整数。 std::stoi 的结果告诉您转换是否成功(即字符串是否表示整数)。如果成功,那么您可以简单地将整数与 12 进行比较。如果不成功,则会抛出 std::invalid_argumentstd::out_of_range 异常。

第一种情况(与std::string比较):

#include <iostream>

int main()
{
    std::string input;
    std::getline(std::cin, input);
    if (input != "1" && input != "2")
        std::cout << "Invalid input!";
}

第二种情况(使用std::stoi):

#include <iostream>

int main()
{
    std::string input;
    std::getline(std::cin, input);
    int n = std::stoi(input); // throws exception if cannot convert to int
    if (n != 1 && n != 2)
        std::cout << "Invalid input!";
}

试试这个:

 #include <iostream>
using namespace std;
int main()
{
    char input;
    cin>>input;
    switch(input)
    {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            cout<<"valid input"<<endl;
        break;

        default : 
            cout<<"Invalid input"<<endl;
    }
    return 0;
}

您可以为所有有效输入定义一个案例,其余的保持默认。
0-9 的整数分别具有 48-57 的 ASCII 值。
如果您有
,此解决方案将无济于事 .输入>9 或输入<0
.输入如 1abc

你也可以这样做

    int whileInt=0;
    int choiceOne_One = 0;
    while(whileInt == 0)
    {
    cin >> choiceOne_One;

    if (choiceOne_One == 1 || choiceOne_One == 2){
             if (choiceOne_One == 1){   
                 whileInt++;
                 cout << "\nYou have died. Be more careful.\n";
             }
             else {
                 whileInt++;
                 cout << "\nYou have survived the alien invasion due to your cunning sense of "
                  "safety.\nCongratulations.\n";
             }
    }
    else {
         cout << "Woah! That wasn't an option! Try Again.\n";        
    }
    }

如果您更改程序以便 cin 将用户的答案放入 std::string,那么您可以对字符串值进行测试。

如果字符串的 length() 大于 1,则不能为 '1' 或 '2'

您还可以进行其他测试,例如 std::isalpha(int ch)

#include <stdio.h>
#include <string>
#include <iostream>

int main(int argc, char * argv[]) {

      std::string value;

      std::cin >> value;

      std::cout << "Value is " << value << "\n";

      std::cout << "length of value is " << value.length() << "\n";

      char ch;

      ch = value.at(0);

      if(std::isalpha(ch)) std::cout << "You did not enter a number" << "\n";

  return 0;
}

robert@debian:/tmp$ g++ -Wall test.cpp

robert@debian:/tmp$ ./a.out 123 值为 123 值的长度为 3

robert@debian:/tmp$ ./a.out 美国广播公司 值为 abc 值的长度为 3 您没有输入数字

可能有点晚了,但我最喜欢的方式是我使用的方式:

#include <iostream>
#include <string>
#include <limits>    
//T is for our variable and lambdaFunc will be our lambda function or
//function pointer
template<typename T, typename lambdaFunc>
auto secureEntry(T& variable, LambdaFunc lFunc, std::string errorMessage) //can ommit error message
{
    while(!(std::cin(variable)) && !lFunc(variable)){
        std::cout << errorMessage << std::endl;
        std::cin.clear();
        std::ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
    }
}
int main(int argc, char* argv[]){
    int mynumber = {0};
    std::string errorMessage = "Please use a number bigger than 0 and lower than 5"
    secureEntry(myNumber, [](int& mynumber) -> bool{
        return mynumber > 0 && mynumber < 5;    
    }, errorMessage)
}