84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
int a; scanf("%d",&a); cin>>a;
ex:我想让用户输入整数,但是如果用户输入的不是我想要的类型如!%$#,abcd....都有什么方法或者函数去判断呢?
光阴似箭催人老,日月如移越少年。
scanf的返回值是正常读取量的数目,所以只要判断返回值即可。
scanf
if(scanf("%d", &a) == 1) printf("OK!"); else printf("Failed to read an integer.");
但scanf比较大的一个坑是其遇到无效字符会停止扫描并将无效字符留在缓冲区中,所以会一直检测到失败,进入死循环。遇到这种问题,可以使用如下方案解决:
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;
当然,这也并非一个好的选择,最好是避免在这种情况下使用scanf,可以先按照字符串进行读取,然后检查字符串合法性,使用一些库函数(如sscanf、isdigit、atoi等等)将字符串转化为整数。
sscanf
isdigit
atoi
我记得大一做过类似的题目,当时都是用正则表达式判断的。
string str; cin >> str; const regex re("\\d+"); if(!regex_match(str, re)) //.... else int num = stoi(str);
scanf
的返回值是正常读取量的数目,所以只要判断返回值即可。但
scanf
比较大的一个坑是其遇到无效字符会停止扫描并将无效字符留在缓冲区中,所以会一直检测到失败,进入死循环。遇到这种问题,可以使用如下方案解决:当然,这也并非一个好的选择,最好是避免在这种情况下使用
scanf
,可以先按照字符串进行读取,然后检查字符串合法性,使用一些库函数(如sscanf
、isdigit
、atoi
等等)将字符串转化为整数。我记得大一做过类似的题目,当时都是用正则表达式判断的。