检查C中是否有正确的输入
问题描述:
这是我的程序。检查C中是否有正确的输入
reprocess:
printf("Enter number: 1,2,3 ");
if(scanf("%d%c", &preproc, &term)!= 2 || term!= '\n'){
printf("Invalid Input");
goto reprocess;
}else{
if ((preproc==1) || (preproc==2) || (preproc==3)){
printf("Correct Input\n");
}else{
printf("Invalid Input %d \n", preproc);
goto reprocess;
}
}
为什么如果我输入一个字符串,它不会停止循环?请指导我。
答
试试这个
if(scanf("%d%c", &preproc, &term)!= 2 || term!= '\n'){
printf("Invalid Input\n");
scanf("%[^\n]");//this will skip the input when there is a non-numeric input.
goto reprocess;
}else{
你明确地写道,如果他们输入一个字符串,然后'转到重新处理;'。你期望什么? – 2014-09-18 23:33:14
@AdamSinclair吧?此代码仅打印“无效输入”(可能后跟一个数字)或“正确输入”。 – 2014-09-18 23:37:12
这只是某种输入检查器。 – user3339866 2014-09-18 23:39:33