2015-01-13 48 views
-1

我是C程序的初學者,我試圖創建一個餐館訂單菜單。 我從用戶輸入「Y」開始開始訂購。 然後我想讓程序繼續下訂單,直到用戶輸入「N」停止。 輸入「N」時,將打印總銷售額。 但我不能做循環,你會介意幫助我嗎?謝謝。 :)如何循環直到用戶在C中輸入N

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
int code; 
float totalPrice=0, totalSales = 0 ; 
char choice, choice1; 

printf("Welcome to Deli Sandwich! Enter Y to start your order!\n"); 
scanf("%c", &choice); 

while(choice=='Y'|| choice=='y') 
{ 
    printf("\n____________________________SANDWICH FILLING______________________________\n"); 
    printf("\n\t\t Menu \t\t Code \t\t Price\n"); 
    printf("\n\t\t Egg \t\t 1 \t\t RM 1.00\n"); 
    printf("\n\t\t Tuna \t\t 2 \t\t RM 2.00\n"); 
    printf("\n\t\t Seafood \t 3 \t\t RM 3.00\n"); 
    printf("\n\t\t Chicken Ham \t 4 \t\t RM 2.50\n"); 

    printf("\nSandwich Filling code: "); 
    scanf("%d", &code); 

    switch(code) 
    { 
    case 1: 
     printf("Egg is picked.\n"); 
     totalPrice+= 1; 
     break; 
    case 2: 
     printf("Tuna is picked.\n"); 
     totalPrice+= 2; 
     break; 
    case 3: 
     printf("Seafood is picked.\n"); 
     totalPrice+= 3; 
     break; 
    case 4: 
     printf("Chicken Ham is picked.\n"); 
     totalPrice+= 2.50; 
     break; 
    default : 
     printf("invalid code."); 

    } 

    printf("\n_____________________________SANDWICH TYPE________________________________\n"); 
    printf("\n\t\t Menu \t\t Code \t\t Price\n"); 
    printf("\n\t\t Half \t\t 1 \t\t RM 3.00\n"); 
    printf("\n\t\t Whole \t\t 2 \t\t RM 5.00\n"); 

    printf("\nSandwich Type code: "); 
    scanf("%d", &code); 

    switch(code) 
    { 
    case 1: 
     printf("Half is picked.\n"); 
     totalPrice+= 3; 
     break; 
    case 2: 
     printf("Whole is picked.\n"); 
     totalPrice+= 5; 
     break; 
    default : 
     printf("invalid code."); 

    } 

    printf("\nThe total price is RM%.2f.\n", totalPrice); 
    printf("Thank You. Please come again!\n"); 

    totalSales+= totalPrice; 

    printf("\nWelcome to Deli Sandwich! Enter Y to start your order!\n"); 
    scanf("%c", &choice); 

} 

printf("\nThe total sales is RM%.2f.\n", totalSales); 

return 0; 

}

再次謝謝:)

回答

0

變化

scanf("%c", &choice); 

scanf(" %c", &choice); // note the space before %c 

這樣做是放棄所有的空白字符,如\nstdin的空格。

當您輸入數據爲scanf時,輸入一些數據並按輸入密鑰scanf消耗輸入的數據並將\n輸入密鑰)留在輸入緩衝區(stdin)中。當scanf%c被稱爲下一次,它將採取\n作爲輸入(由前scanf遺留),並不會等待進一步的輸入。

在你的代碼,

scanf("%c", &choice); 

while循環之前消耗你輸入的字符和樹葉在stdin\n。至於爲什麼

scanf("%d", &code); 

等待輸入的是,%d格式說明跳過空格字符,而%c沒有。

+0

哦,是嗎?萬分感謝! – njl

0
scanf(" %c", &choice); 

通過將前%c

0

簡單%C之前添加空間的空間忽略在輸入的端部的換行字符

0

ENTER按鍵提供輸入之後被存儲輸入到輸入緩衝區stdin中,並考慮有效的輸入用於%c格式說明符的循環scanf() s。爲了避免掃描存儲\n,您需要更改像

scanf(" %c", &choice); 
    ^
     | 

這導致空間表示你的代碼忽略任何前導空格或空白樣字符(包括\n)和掃描第一個非 - 空白字符。[在你的情況下,y/Y/n ...]

相關問題