int a;
scanf("%d",&a);
cin>>a;
ex:我想让用户输入整数,但是如果用户输入的不是我想要的类型如!%$#,abcd....都有什么方法或者函数去判断呢?
大家讲道理2017-04-17 11:36:21
The return value of
scanf
is the number of normal reads, so just judge the return value.
if(scanf("%d", &a) == 1)
printf("OK!");
else
printf("Failed to read an integer.");
But a big pitfall of scanf
is that it will stop scanning when it encounters invalid characters and leave invalid characters in the buffer, so it will always detect failures and enter an infinite loop. If you encounter this problem, you can use the following solutions to solve it:
int a;
while(1 != scanf("%d", &a)) {
fflush(stdin); // 刷新缓冲区
cout << "Invalid input! Please check and input again: ";
}
cout << "a = " << a << endl;
cout << "Test finished!";
return 0;
Of course, this is not a good choice. It is best to avoid using scanf
in this situation. You can read the string first, then check the string validity, and use some library functions (such as sscanf
, isdigit
, atoi
, etc.) to convert a string into an integer.
PHPz2017-04-17 11:36:21
I remember doing similar questions in my freshman year, and they were all judged using regular expressions.
string str;
cin >> str;
const regex re("\d+");
if(!regex_match(str, re))
//....
else
int num = stoi(str);