【发布时间】:2019-01-28 03:19:30
【问题描述】:
我有一段代码可用于输入验证,我需要更多解释它为什么起作用。垃圾变量从 getchar 读取一个字符并检查它是否不等于 EOF 的行让我有点困惑。它的目的是从用户那里读取垃圾输入,并允许用户重新输入输入。我的问题是,这条线到底是如何工作的?
int steps = 0;
int true;
int garbage;
printf("Enter the integer increment number in the range ");
printf("of[%d - %d]: ", minInput, maxInput);
true = scanf("%d", &steps);
/* INPUT VALIDATION */
while (!true || isdigit(steps) ||(steps < minInput || steps > maxInput) ){
while ((garbage = getchar()) != EOF && garbage != '\n') {
} // end while;
printf("Invalid input... please enter a number in the range ");
printf("of[%d - %d]: ", minInput, maxInput);
true = scanf("%d", &steps);
}// end while
【问题讨论】:
-
isdigit(steps)是我看到的第一个逻辑有问题的东西。它从未被读取为字符 (%c),它被读取为整数十进制 (%d)。该函数所做的只是测试一个字符在'0'...'9'中的成员资格。0..9的值(整数值;不是字符)将永远导致isdigit(steps)为真,因此在您的条件中毫无意义。 -
true是一个相当不明智的变量名称 - 它通常指的是一个值而不是变量,并且会与符号的stdbool.h定义冲突并排除 C++ 编译。 -
当
scanf("%d", &steps)返回EOF时,while (...) { }是一个无限循环。
标签: c validation input