检查input值是一个整数

我input这个,它要求用户input两个整数,然后将成为variables。 从那里开始简单的操作。

如何让电脑检查input的内容是否是整数? 如果没有,请求用户键入一个整数。例如:如果有人input“a”而不是2,那么它会告诉他们重新input一个数字。

谢谢

#include <iostream> using namespace std; int main () { int firstvariable; int secondvariable; float float1; float float2; cout << "Please enter two integers and then press Enter:" << endl; cin >> firstvariable; cin >> secondvariable; cout << "Time for some simple mathematical operations:\n" << endl; cout << "The sum:\n " << firstvariable << "+" << secondvariable <<"="<< firstvariable + secondvariable << "\n " << endl; } 

你可以这样检查:

 int x; cin >> x; if (cin.fail()) { //Not an int. } 

此外,你可以继续得到input,直到你得到一个int通过:

 #include <iostream> int main() { int x; std::cin >> x; while(std::cin.fail()) { std::cout << "Error" << std::endl; std::cin.clear(); std::cin.ignore(256,'\n'); std::cin >> x; } std::cout << x << std::endl; return 0; } 

编辑:为了解决下面有关input如10abc的评论,可以修改循环接受一个string作为input。 然后检查string中的任何字符而不是数字,并相应地处理该情况。 在这种情况下,不需要清楚/忽略inputstream。 之后,将string转换回整数。 比如..我的意思是,这只是袖口。 可能有更好的办法。

 #include <iostream> #include <string> int main() { std::string theInput; int inputAsInt; std::getline(std::cin, theInput); while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) { std::cout << "Error" << std::endl; if( theInput.find_first_not_of("0123456789") == std::string::npos) { std::cin.clear(); std::cin.ignore(256,'\n'); } std::getline(std::cin, theInput); } std::string::size_type st; inputAsInt = std::stoi(theInput,&st); std::cout << inputAsInt << std::endl; return 0; } 

如果istream无法插入,则会设置失败位。

 int i = 0; std::cin >> i; // type a and press enter if (std::cin.fail()) { std::cout << "I failed, try again ..." << std::endl std::cin.clear(); // reset the failed state } 

你可以在一个do-while循环中设置它,以获得正确的types(在这种情况下是int )。

有关更多信息,请访问http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly

c中有一个叫做isdigit()的函数。 这将适合你很好。 例:

 int var1 = 'h'; int var2 = '2'; if( isdigit(var1) ) { printf("var1 = |%c| is a digit\n", var1 ); } else { printf("var1 = |%c| is not a digit\n", var1 ); } if( isdigit(var2) ) { printf("var2 = |%c| is a digit\n", var2 ); } else { printf("var2 = |%c| is not a digit\n", var2 ); } 

从这里

您可以使用variables名称本身来检查一个值是否是一个整数。 例如:

 #include <iostream> using namespace std; int main (){ int firstvariable; int secondvariable; float float1; float float2; cout << "Please enter two integers and then press Enter:" << endl; cin >> firstvariable; cin >> secondvariable; if(firstvariable && secondvariable){ cout << "Time for some simple mathematical operations:\n" << endl; cout << "The sum:\n " << firstvariable << "+" << secondvariable <<"="<< firstvariable + secondvariable << "\n " << endl; }else{ cout << "\n[ERROR\tINVALID INPUT]\n"; return 1; } return 0; } 

你可以使用:

 int a = 12; if (a>0 || a<0){ cout << "Your text"<<endl; } 

我很确定它的工作原理。