As @SomeProgrammerDude pointed outisdigit
检查一个字符是否是数字。你传递一个整数。它会将该整数解释为字符,因此它会认为10
是换行符,而43
是+
。如果你给它50
它会通过,因为那是字符2
。如果scanf
失败,请检查current
,因为那将包含垃圾。相反,请检查返回值scanf
,它会告诉您它匹配了多少个项目。
int counter = 0;
int largest = 0;
// It's safer to check for X < BOUND than X != BOUND in case
// X happens to go over the BOUND.
while (counter < 10) {
int current;
printf("%s", "Enter non-negative number: ");
// What if `scanf` didn't get a number?
if(scanf("%d", ¤t) != 1) {
puts("That doesn't look like a number");
}
// What if it isn't positive?
else if(current < 0) {
puts("Invalid number. Number must be positive. \n");
}
// Now that all the error conditions have been checked...
else {
if (current > largest)
{
largest = current;
}
counter++;
}
}
printf("%d", largest);
但仍然存在问题。如果你得到一个无效的数字,代码将进入无限循环。这是many, many, many problems with scanf
之一,特别是this one。
问题是scanf
不读取行,它的读数与您告诉的一样多。如果它读不了那么多,它就把它留在缓冲区中。如果scanf
失败,则会在stdin
上留下输入。当你再次阅读时,你会看到相同的输入并再次失败。如果线路上有任何额外输入,如10 foo
它将读取10
,然后将foo
保留在缓冲区中,以便在下一次拨打电话时读取scanf
。
一般的解决方案是逐行读取输入并解析行。使用fgets
读取该行并使用sscanf
扫描字符串。
int counter = 0;
int largest = 0;
char line[255];
while (counter < 10) {
int current;
printf("%s", "Enter non-negative number: ");
fgets(line, sizeof(line), stdin);
if(sscanf(line, "%d", ¤t) != 1) {
puts("That doesn't look like a number");
}
...and the rest is the same...
}
这保证你永远不会陷入无限循环。尽管如果输入大于line
,它可能需要循环几次以获得所有输入。
您是否检查'scanf'返回的值?你为什么认为'current'包含有效数据? –
直到你写出10位数的** ASCII代码** ... –
@WilliamPursell yes我在描述中说过它会返回一个非常大的负值(-8995460) – Andrew