检查输入值是一个整数 [英] Checking input value is an integer
本文介绍了检查输入值是一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我输入这个,它要求用户输入两个整数,然后将变成变量。从那里将进行简单的操作。
I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
如何让计算机检查输入的内容是否为整数?如果没有,请让用户输入一个整数。例如:如果有人输入a而不是2,那么它会告诉他们重新输入一个数字。
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
感谢
#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.
}
此外,您可以继续获取输入,直到获得int: / p>
Furthermore, you can continue to get input until you get an int via:
#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;
}
这篇关于检查输入值是一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文