我正在研究這個示例練習,並且所有事情都按照我的意願工作,但有一種行爲我不明白。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