2016-12-13 86 views
1

您好考慮下面的簡單的程序:炭未按預期運行在C

int main(void) 
{ 
    //exercise 1 

    float num2; 
    printf("please enter a number \n"); 
    scanf_s("%f", &num2); 
    printf("the number multiple by 3 is %3.3f\n", num2 * 3); 

    //exercise 2 
    char ch1, ch2, ch3, ch4; 

    printf("enter a word with four char\n"); 
    ch1 = getchar(); 
    ch2 = getchar(); 
    ch3 = getchar(); 
    ch4 = getchar(); 

    printf("the chars in reverse order are\n"); 
    putchar(ch4); 
    putchar(ch3); 
    putchar(ch2); 
    putchar(ch1); 
    putchar('\n'); 
} 

輸出爲:

please enter a number 
2 
the number multiple by 3 is 6.000 
enter a word with four char 
ffff 
the chars in reverse order are 
fff 

3字符打印到控制檯,如果我移動鍛鍊的碼塊2以上1:

int main(void) 
{ 
    //exercise 2 
    char ch1, ch2, ch3, ch4; 

    printf("enter a word with four char\n"); 
    ch1 = getchar(); 
    ch2 = getchar(); 
    ch3 = getchar(); 
    ch4 = getchar(); 

    printf("the chars in reverse order are\n"); 
    putchar(ch4); 
    putchar(ch3); 
    putchar(ch2); 
    putchar(ch1); 
    putchar('\n'); 

    //exercise 1 

    float num2; 
    printf("please enter a number \n"); 
    scanf_s("%f", &num2); 
    printf("the number multiple by 3 is %3.3f\n", num2 * 3); 
} 

結果如預期:

enter a word with four char 
ffff 
the chars in reverse order are 
ffff 
please enter a number 
2 
the number multiple by 3 is 6.000 

我想知道爲什麼它在工作,當我更改代碼塊的順序時,我該如何解決它,謝謝。

+0

極爲常見的常見問題。輸入緩衝區中留有新的行字符。例如查看鏈接副本,「當* scanf()無法按預期工作時」部分。 – Lundin

回答

4

想知道爲什麼它的工作時,我改變順序代碼塊,我怎麼能解決這個問題,

這是因爲scanf_s("%f", &num2);離開換行字符輸入緩衝區。所以你的第一個getchar();將解釋該換行符爲ch1

對於這種情況,一種無聲的前getchar會做:

getchar(); // will consume the remaining newline from stdin 
ch1 = getchar(); 
ch2 = getchar(); 
ch3 = getchar(); 
ch4 = getchar(); 
+1

使用fflush將不起作用,因爲它沒有爲輸入緩衝區定義。請從答案中刪除該部分,因爲它不正確,並導致調用未定義的行爲。 – Lundin

+0

啊對,'fflush'不是標準的,tks。同意並刪除該部分.. – artm

2

有一個換行符,當你輸入的第一個浮點數,它是輸入由調用getchar一個字符。解決這個問題的另一種方法是讓整條生產線如使用fgets一個字符串,然後用你想要的任何格式解析它:

char line[512]; 
printf("please enter a number \n"); 
fgets(line, sizeof line, stdin); // the newline is consumed here 
sscanf(line, "%f", &num2); 

ch1 = getchar(); // working as expected