如何使用while循环继续询问输入,直到输入正确(C)?

时间:2017-08-04 04:05:13

标签: c loops input

我想使用while循环来向用户询问正确的输入,直到给出它为止。这可能与scanf()有关吗?我知道如果输入不匹配,它将保持未分配状态并保存为由第二个scanf()捕获。

以下程序会永远运行,并且在第一次输入错误时不会要求我输入第二个输入。

#include<stdio.h> 
/* Check the input, if the input does not contain a single integer value, 
then keep asking for the integer value */
/* I used a counter variable so that the program does not run on forever */
int
main (int argc, char * argv[]){
    int counter = 10, items = 0, input = 0;
    while (counter){
        printf("input an integer value: ");
         items = scanf("%d",&input);
         if (items == 1){
             printf("successfully read an item");
             break;
         }   
         else{
             counter --;
             input = 0;
             printf("failed to read an item, please try again\n");
         }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

无限循环的原因是扫描错误,如果没有读取则返回0,如果有错误则返回EOF。无论流上的非整数项是否从未被取消,因此scanf调用将保持返回相同的0值,因为它无法继续,直到它被删除或跳过(此处为其他答案)。

解决此问题的一种方法是清除缓冲区。这是解决问题的一种方法。

char tmp;
...
items = scanf("%d",&input);    
if(items!=1){
  // perhaps printf('That was not a number\n');
  while(scanf('%c',&tmp)!=EOF);
}
else if(items==1){
   ... //hooray you read an item, it's value is in input
}
else{
      // the user quit with a Control-D or something.
}

P.S。我喜欢关于如何摆脱scanf的reference by Felix

答案 1 :(得分:-3)

好的,经过一些测试和搜索,我发现你可以使用fseek(stdin,0,SEEK_END);解决问题。

尝试:

#include<stdio.h>
/* Check the input, if the input does not contain a single integer value,
   then keep asking for the integer value */
/* I used a counter variable so that the program does not run on forever */
int
main (int argc, char * argv[]){
        int counter = 10, items = 0, input = 0;
        while (counter){
                printf("input an integer value: ");
                items = scanf("%d",&input);
                if (items == 1){
                        printf("successfully read an item");
                        break;
                }
                else{
                        counter --;
                        input = 0;
                        printf("failed to read an item, please try again\n");
                        fseek(stdin,0,SEEK_END);
                }
        }
        return 0;
}