2016-03-06 68 views
-1

解決這對我來說,因爲我真的不知道有人可以解決這個代碼塊?

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

int main() { 
    char ans; 

    printf("1. The patients felt _____ after taking the medicine.\n"); 
    printf("\t a. best\n\t b. better\n\t c. good\n\n"); 
    scanf("%c", &ans); 

    if (ans == 'b') { 
     printf("2. I ______ my essay by the time the bell rings.\n"); 
     printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n"); 
     scanf("%c", &ans); 
    } else { 
     printf("YOU FAILED!"); 
    }; 
    return 0; 
} 

如果你回答您下次繼續對第一個問題,回答第二個問題,但問題是,即使有我不能鍵入答案scanf

+0

刪除你的分號後你的分號,然後嘗試運行,我能夠正確運行你的代碼,並給出了答案,再次嘗試運行 –

+1

用適當的標題更新您的查詢。 – Prasad

+1

不要更改代碼在問題中,使用** EDIT **段落添加到問題中,修改問題使評論和回答不一致。 – chqrlie

回答

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

int main() { 
    char ans; 

    printf("1. The patients felt _____ after taking the medicine.\n"); 
    printf("\t a. best\n\t b. better\n\t c. good\n\n"); 
    scanf("%c", &ans); 

    if (ans == 'b') { 
     printf("2. I ______ my essay by the time the bell rings.\n"); 
     printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n"); 
     scanf(" %c", &ans); 
    } else { 
     printf("YOU FAILED!"); 
    }; 

    return 0; 
} 

的區別是:

scanf(" %c",&ans); 
    ^this space this will read whitespace characters (which newline also is) 
     until it finds a non space character. 

scanf沒有消耗,在緩衝呆從第一scanf呼叫\n字符。

我試試這個,它的工作原理!

+0

謝謝!現在解決 –

+1

如果答案對你有幫助,你應該接受答案,用這種方式http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work來幫助未來的人同樣的問題。你不接受答案,也許你是新來的 – PRVS

+0

是的,我是新的。無論如何tnx –

1

第二個scanf("%c"...)讀取第一個scanf在標準輸入中留下的換行。您可以通過讀取一個多餘的字符這種方式解決這個問題:

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

int main() { 
    char ans; 

    printf("1. The patients felt _____ after taking the medicine.\n"); 
    printf("\t a. best\n\t b. better\n\t c. good\n\n"); 
    scanf("%c%*c", &ans); 

    if (ans == 'b') { 
     printf("2. I ______ my essay by the time the bell rings.\n"); 
     printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n"); 
     scanf("%c%*c", &ans); 
    } else { 
     printf("YOU FAILED!"); 
    } 
    return 0; 
} 

scanf("%c%*c", &ans)讀入一個字符,並將其存儲到ans變量,然後讀取另一個字符,將其丟棄。這樣\n被用戶鍵入後丟棄b

另一種方法是忽略空白字符與scanf(" %c", &ans):在scanf格式指示scanf閱讀並忽略任何空白字符。第一種方法的優點是,如果用戶在輸入單個字符後輸入一個字符,則在scanf之後沒有留下字符,第二種方法將使\n處於未決狀態,但以下scanf將忽略它。

相關問題