2015-01-12 175 views
2

任何人都可以請解釋爲什麼我的while循環不會結束,當我輸入字符'Q'?它不停地循環,即使我我的布爾值設置爲false,當用戶輸入「Q」,它假設scanf函數爲char input後結束。雖然循環在C

我的代碼:

#include <stdio.h> 
typedef int bool; 
#define true 1 
#define false 0 

int main(void) { 
    char input; 
    char output; 
    bool tf = true; 

    printf("Welcome to the Coder!\n"); 

    while (tf) { 
     printf("Choose Input (H,A,B,Q) : "); 
     scanf_s(" %c\n", &input); 

     if (input == 'Q') { 
      tf = false; 
     } 
     else { 
      printf("Choose Output (H,A,B) : "); 
      scanf_s(" %c\n", &output); 
     } 
    } 

    return 0; 
} 
+2

您是否在輸入Q後按下輸入? – immibis

+3

又一個scanf問題? –

+0

是的,我確實按下輸入 – Impalerz

回答

4

的問題是scanf_s的奇怪情況。雅閣MSDN,你讀使用此語法單個字符:

scanf_s(" %c", &input, 1); 

取下scanf_s\n並添加1個參數,所以它知道到只讀1個字符。

+0

這解決了這個問題,謝謝。在%c之後我並不需要\ n – Impalerz

3

我懷疑你是在控制檯上輸入小寫字母問:

我建議你到你的代碼更改爲:

if (input == 'Q' || input == 'q') { 
    tf = false; 
} 
+2

或者就此而言,'#include '和'if(toupper(input)=='Q')' –

1

如果

(input == 'Q' || input == 'q') 

而且你爲什麼要添加typedef int bool;你應該補充的嗎?這是不需要的。 。

我更換scanf_sscanf因爲我的編譯器不能識別它(一不小心解決問題

,因爲它是更好,當我編譯這個沒有錯誤

編譯 - >Compiled Code