【发布时间】:2022-01-11 07:32:22
【问题描述】:
我正在编写一个程序,要求用户输入两个数字之间的数字。一个最小值和一个最大值。用户必须在这些参数中输入数字,程序才能成功运行。
这是调用 getIntFromRange 的函数。
void test04_getIntFromRange(void)
{
int intValue;
printf("TEST #4 - Instructions:\n"
"1) Enter the number '14' [ENTER]\n"
":>");
// You may want to comment the next line if you have not yet created the getInteger function:
intValue = getIntFromRange(-40, 14);
printf("////////////////////////////////////////\n");
printf("TEST #4 RESULT: ");
if (intValue == 14)
{
printf("*** PASS *** \n");
}
else
{
printf("### FAILED ###\n");
}
printf("////////////////////////////////////////\n\n");
}
这是我为getIntFromRange写的代码
int getIntFromRange(int lower_bound, int upper_bound)
{
int value = 0;
scanf("%d", &value);
while (scanf("%d", &value) != 1) {
printf("Error: Value must be an integer: ");
scanf("%*s");
clearStandardInputBuffer();
}
while (value > upper_bound || value < lower_bound) {
printf("ERROR: Value must be between %d and %d inclusive: ", lower_bound, upper_bound);
scanf("%d", &value);
}
}
问题是当用户输入14时它没有立即注册。在注册代码之前我必须多次按Enter。这是程序通过前的输出。
TEST #4 - Instructions:
1) Enter the number '14' [ENTER]
:>14
14
////////////////////////////////////////
TEST #4 RESULT: *** PASS ***
////////////////////////////////////////
Assignment #1 Milestone #1 completed!
【问题讨论】:
-
getIntFromRange读取一个数字两次,一次是在没有错误检查的开头,另一次是在while循环条件中。第一个被丢弃。 -
ChecksOverStripes,为什么
scanf("%*s");在clearStandardInputBuffer();之前?