2014-09-18 61 views
-2

假設char c是來自用戶的單個字符的輸入。在C中打印循環中的字符輸入

if (c != 'A' && c != 'B' && c != 'C' && c != 'D') { 
    int t = 1; 
    while (t = 1) { 
    printf("%c is an invalid input. Valid cases are A-D.\n", c); 
    scanf("%c", &input); /* Space for taking care of whitespace */ 
    c = lowToUp(c); /* If c is lowercase, convert to uppercase */ 
    if (c == 'A' || c == 'B' || c == 'C' || c == 'D') { 
     break; 
    } 
    } 
} 

我試圖顯示此錯誤消息並繼續循環,直到用戶輸入有效的char值。

循環本身很好,但輸出不是。如果我進入X,

X is an invalid input. Valid cases are A-D. 

is an invalid input. Valid cases are A-D. 

無形\ n c鍵的實際值後,一直沒有困擾我在我的計劃中,除了這個其他任何部分。

我該如何擺脫它?

+0

您正在進入循環兩次。一次輸入'X',一次輸入'\ n'。 – 5gon12eder 2014-09-18 23:46:18

+2

c因爲新輸入被放入「輸入」,因此c在循環中不會發生變化(除了上殼)。你確定這是你正在運行的代碼嗎? – 2014-09-18 23:59:20

+0

是的,那是我爲結果運行的確切代碼。 – whdPdnjs 2014-09-19 00:09:54

回答

2

在每個scanf之後,您需要刷新輸入緩衝區。例如: -

int c; 
.... 
scanf (....) 
do { c = getchar(); } while (c != '\n' && c != EOF);  /* flush input buffer */ 
+0

現在它似乎只顯示我的原始結果的第二部分,用\ n代替c。 – whdPdnjs 2014-09-19 00:03:28

+0

@whdPdnjs您可能在代碼中的某個輸入中留下了一些輸入中的數據 – 2014-09-19 00:04:28

+0

剛剛發現它實際上並沒有在\ n之前的char值中讀取,所以即使我在第二個循環中輸入了有效值並且此後,循環正在進行中。 – whdPdnjs 2014-09-19 00:08:31

0

正如你在/* Space for taking care of whitespace */說,格式字符串的內部空間將消耗任何數量的空格中。但是,你沒有放過任何東西。

scanf(" %c",&input); 
    //^ notice the space is inside the string, not before it like you did 
+0

這樣做是因爲編輯器和服務器之間存在scanf(「%c」,&input)這個特定問題;由於某些原因,在同一個項目上工作的其他人或教師不知道的原因,\ n所帶的價值將會是\ n。無論我輸入什麼內容,刪除該空間都將返回\ n,從而使循環難以實現。 – whdPdnjs 2014-09-19 00:19:28