C scanf在循环中输入无效

时间:2016-03-09 17:56:10

标签: c buffer scanf stdin buffer-overflow

我必须在if语句中执行此操作,或者如果设置了诸如“17d”之类的无效输入,则它将变为无限循环。为什么?我认为有一些缓冲区,但scanf从stdin读取而不是从流中读取?

  int age;

  while (age != 0) {
    printf("How old are you? ");

    if(scanf("%d", &age) > 0) {
      printf("You are %d years old!\n", age);  
    } else {
      break;
    }

  }

1 个答案:

答案 0 :(得分:1)

scanf不成功时,它会在流中保留输入。您需要忽略该行的其余部分并要求用户再次提供输入。您可以添加如下函数:

void ignoreRestOfLine(FILE* fp)
{
   int c;
   while ( (c = fgetc(fp)) != EOF && c != '\n');
}

并从main

调用它
if(scanf("%d", &age) > 0) {
  printf("You are %d years old!\n", age);  
} else {
  // Ignore rest of the line and continue with the loop.
  ignoreRestOfLine(stdin);
}

另一个选择是一次读取一行数据并使用sscanf从行中提取数字。

char line[100]; // Make it large enough
while (age != 0)
{
   printf("How old are you? ");

   if ( fgets(line, sizeof(line), stdin) == NULL )
   {
      // Problem reading a line of text.
      // Deal with it.
      break;
   }
   else
   {
      if(sscanf(line, "%d", &age) > 0)
      {
         printf("You are %d years old!\n", age);  
      }
   }

   // Try to read again
}