C/C++如何判断用户输入是否合法?
大家讲道理
大家讲道理 2017-04-17 11:34:21
0
2
575
int a;
scanf("%d",&a);
cin>>a;

ex:我想让用户输入整数,但是如果用户输入的不是我想要的类型如!%$#,abcd....都有什么方法或者函数去判断呢?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
大家讲道理

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.

PHPzhong

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template