我正在研究这个示例练习,并且所有事情都按照我的意愿工作,但有一种行为我不明白。scanf验证位于并等待另一个输入。为什么?
当提供输入:如果我连续无效输入一切似乎很好。但如果我在第一个问题的情况下输入了一个不同于1,2,3的数字,或者在第二个问题的情况下输入了一个1,2,那么程序就会坐在那里直到给出新的输入。如果另一个无效条目被创建,它将返回错误“无效条目”消息,并且如果输入了一个合适的数字,那么一切都会顺利进行。
我不明白为什么它停下来等待第二个输入...任何人?
谢谢你们。
#include <stdio.h>
static int getInt(const char *prompt)
{
int value;
printf("%s",prompt);
while (scanf("%d", &value) !=1)
{
printf("Your entry is invalid.\nGive it another try: %s", prompt);
getchar();
scanf("%d", &value);
}
return value;
}
int main() {
int wood_type, table_size, table_price;
printf("Please enter ");
wood_type = getInt("1 for Pine, 2 for Oak, and 3 for Mahogany: ");
printf("Please enter ");
table_size = getInt("1 for large, 2 for small: ");
printf("\n");
switch (wood_type) {
case 1:
table_price = (table_size == 1)? 135:100;
printf("The cost of for your new table is: $%i", table_price);
break;
case 2:
table_price = (table_size == 1)? 260:225;
printf("The cost of for your new table is: $%i", table_price);
break;
case 3:
table_price = (table_size == 1)? 345:310;
printf("The cost of for your new table is: $%i", table_price);
break;
default:
table_price = 0;
printf("The cost of for your new table is: $%i", table_price);
break;
}
}
兄弟,我无法将你的代码运行良好,理解您的问题在我的机器..如果我在第一排第二个它打印提供1或2或3,然后1或2一些现金..如果输入1行不是1 2 3打印0和最后如果在第一行我的输入是1 2 3和第二行它不是1或2然后也打印一些金额。我错过了什么。我读了你的代码并在我的机器上试过。我想我不明白你的问题 – Asis 2014-10-11 15:18:01
对于第一个输入,尝试输入一个字母,然后输入数字5。输入5后,它会让我挂在那里,直到我输入另一个字母,或1,2或3。 – 2014-10-11 15:22:18
哦!是啊挂我...大声笑 – Asis 2014-10-11 15:24:19