2014-09-18 67 views
-1

这是我的程序。检查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; 

     } 
    } 

为什么如果我输入一个字符串,它不会停止循环?请指导我。

+0

你明确地写道,如果他们输入一个字符串,然后'转到重新处理;'。你期望什么? – 2014-09-18 23:33:14

+0

@AdamSinclair吧?此代码仅打印“无效输入”(可能后跟一个数字)或“正确输入”。 – 2014-09-18 23:37:12

+0

这只是某种输入检查器。 – user3339866 2014-09-18 23:39:33

回答

1

试试这个

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{ 
相关问题