输入无效的循环中的C scanf [英] C scanf in a loop with invalid input

查看:91
本文介绍了输入无效的循环中的C scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须执行if语句,否则,如果设置了一些无效的输入(例如 17d),它将陷入无限循环。为什么呢我认为有缓冲区但scanf会从stdin读取而不是从流中读取吗?

I have to do this if statement , or it turns in an infinite loop if some invalid input like "17d" is set. Why ? I think something with buffer but scanf reads from stdin not from stream?

  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;
    }

  }


推荐答案

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

When scanf does not succeed, it leaves the input in the stream. You need to ignore the rest of the line and ask the user to provide the input again. You can add a function like:

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);
}

另一种选择是一次读取一行数据并使用<$

Another option is to read the data a line at a time and use sscanf to extract the number from the line.

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
}

这篇关于输入无效的循环中的C scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆