当用户在scanf()中输入错误的数据类型时如何解决无限循环?

问题描述 投票:0回答:2

C初学者在这里。对于下面的程序,每当用户输入字符或字符串时,都会进入无限循环。在仍然使用scanf的情况下如何解决?与使用scanf相比,编写此程序的更好方法是什么?感谢那些会回答的人。

#include <stdio.h>
#include <ctype.h>

int main() {

int rounds = 5;

do {
printf("Preferred number of rounds per game. ENTER NUMBERS ONLY: ");
scanf("%d", &rounds);   
} while(isdigit(rounds) == 0);

return 0;   
}
c loops scanf infinite
2个回答
1
投票

使用'scanf'要求格式化输入。 Scanf处理错误输入的能力非常有限。常见的解决方案是按照以下结构使用fgets / sscanf:

   char buff[256] ;
   int rounds = 0 ;
   while ( fgets(buff, sizeof(buff), stdin) ) {
      if ( sscanf(buff, "%d", &rounds) == 1 ) {
          // additional verification here
          break ;
      } ;
   } ;
   // Use rounds here ...

fgets / sscanf将允许从解析错误中恢复-错误的输入行将被忽略。根据要求,这可能是可接受的解决方案。


0
投票

更改

scanf("%d", &rounds);

收件人

int ret;

if ((ret = scanf(" %d", &rounds)) != 1) { // Skip over white space as well
   if (ret == EOF) break;
   scanf("%*[^\n\r]"); // Consume the rest of the line
}
© www.soinside.com 2019 - 2024. All rights reserved.