【发布时间】:2020-02-14 11:31:44
【问题描述】:
这里是 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()的返回值,看看是否有错误,对于初学者来说。 -
另外,
isdigit()在这里也不合适,除非您希望人们输入数字字符的 ascii 值。 -
不要使用
scanf()。f代表“格式化”。用户输入未格式化。 -
@AndrewHenle 同意用户输入未格式化,但不能同意
scanf是。如果scanf真的是为格式化输入而设计的,那么像%d %d\n%d %d这样的格式字符串将无法读取1 2 3 4或1\n2\n3\n4。