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 将允许从解析错误中恢复 - 错误的输入行将被忽略。根据要求,这可能是可接受的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)