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;
}
使用'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将允许从解析错误中恢复-错误的输入行将被忽略。根据要求,这可能是可接受的解决方案。
更改
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
}