2015-07-10 98 views
1

當我運行我的程序時,它會詢問命令,當您鍵入a,b或c時,它會提示您根據您選擇的值給出該字母。列出的任何其他命令顯示統計信息我的小問題是,當我在一個有效的命令類型,我的「無效的命令」的警告彈出,即使它的工作原理代碼運行,但表示無效

#include <stdio.h> 

int main(void) 
{ 
    double a = 0; 
    double b = 0; 
    double c = 0; 
    double d = 0; 
    double e = 0; 
    double f = 0; 
    double g = 0; 
    double h = 0; 
    double i = 0; 

    char command = '\0'; 

    printf("\n  Welcome\n"); 
    printf("  Aquapodz Stress Analysis Program\n"); 
    printf(" ==================================\n"); 
    while (command != 'x'); 
    { 
     printf("\n\n(a), (b), or (c), enter trial data for  vendor.\n(f)ail-rate,  (m)ean stress, (s)ummary, e(x)it\n"); 
     printf("Please enter a command"); 
     scanf("%c", &command); 

     if (command == 'a') 
     { 
     printf("Please enter stress values (GPa) for this trial."); 
     scanf("%lf", &a); 
     scanf("%lf", &b); 
     scanf("%lf", &c); 
     } 
     else if (command == 'b') 
     { 
     printf("Please enter stress values (GPa) for this trial."); 
     scanf("%lf", &d); 
     scanf("%lf", &e); 
     scanf("%lf", &f); 
     } 
     else if (command == 'c') 
     { 
     printf("Please enter stress values (GPa) for this trial."); 
     scanf("%lf", &g); 
     scanf("%lf", &h); 
     scanf("%lf", &i); 
     } 
     else if (command == 'f') 
     { 

     printf("Average failure rate:\nAzuview:%f\nBublon:%f \nCryztal:%f\n",  a+b+c, d+e+f, g+h+i); 
     } 
     else if (command == 'm') 
     { 
     printf("Average mean stress:\nAzuview:%f\nBublon:%f\nCryztal:%f\n",   a+b+c/3, d+e+f/3, g+h+i/3); 
     } 
     else if (command == 's') 
     { 
     print("Total (pass/fail) so far:\nAzuview:%f(%f/0)\nBublon:%f(%f/0)  \nCryztal:%f(%f/0)\n", a+b+c, a+b+c, d+e+f, d+e+f, g+h+i, g+h+i); 
     } 
     else if (command == 'x') 
     { 

     } 
     else 
     { 
     printf("Invalid Command! Please Try Again :)"); 
     } 

    } 
    printf("Goodbye, Please Come Again!"); 
    return 0; 
} 

回答

1
scanf("%c", &command); 

的問題。您最終將前一個電話的剩餘換行符讀入scanf。使用

scanf(" %c", &command); 
1

當您輸入任何值時,還有一個換行符,當您按下回車鍵時會被輸入。由於關你scanf模式匹配的\n,它停留在緩衝區中,被拾起的下一個scanf

所以不是這樣的:

scanf("%c", &command); 

這樣做:

scanf("%c\n", &command); 

並且在其他地方使用scanf

+0

如果在輸入流中留下的換行符來自'scanf(「%lf」,&i);'。 –

+0

'這就是爲什麼我提到所有'scanf'調用都需要類似的修復。 – dbush

相關問題