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

C++ How to protect against invalid input?

本文关键字:输入 无效 何防止 C++      更新时间:2023-10-16

在我的程序中,我希望用户在两个选项之间进行选择。简单地说,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中工作,请帮助我解决这个问题。一定会不胜感激。

试试这个:

#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 之间的整数的 ASCII 值分别为 48-57。
如果您有输入>9 或输入<0
,则
此解决方案将没有帮助。 输入,例如 1ABC

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

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

你也可以这样做

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

尝试用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!";
}

如果您更改程序,以便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++ -墙测试.cpp

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

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