当scanf在c中返回0并且不起作用时

时间:2015-12-31 23:53:52

标签: c scanf

'当没有成功的任务时'我知道scanf返回0表示它,但这是唯一的吗?这是我的代码:

 #include<stdio.h>
  int main(void) {
      int val,x;
      x=scanf("%d",&val);
     if(x==1)
       printf("success!");
     else{
       printf("try again\n");
       scanf("%d",&val);
      }
   return 0;
 }

如果我输入一个数字,它工作正常,但如果我输入一个字符scanf不再工作,这就是我得到的:

   k
   try again
   process returned 0 (0x0)  execution time :2.578 s
   press any key to continue.
   _

意味着它不允许我输入新值,为什么会这样?代码中有什么问题吗?如果是的话我该如何解决?我应该停止使用scanf吗?

2 个答案:

答案 0 :(得分:7)

scanf不起作用时,无效数据仍保留在流中。在输入更多数据之前,您必须先从流中读取并丢弃数据。

#include<stdio.h>
int main(void) {
   int val,x;
   x=scanf("%d",&val);
   if(x==1)
      printf("success!");
   else{
      // Discard everything upto and including the newline.
      while ( (x = getchar()) != EOF && x != '\n' );
      printf("try again\n");
      scanf("%d",&val);
   }
   return 0;
}

答案 1 :(得分:3)

scanf系列函数按规定被破坏,绝不能用于任何事情。

正确编写此程序的方法是使用getline(如果可用)或fgets来读取整行用户输入。然后使用strtol将输入转换为机器整数,注意检查错误:

errno = 0;
result = strtol(line, &endptr, 10);
if (endptr == line || *endptr != '\n' || errno)
   // invalid input