2011-12-04 50 views
3

有人能解釋我爲什麼我看到的printf的雙輸入()函數while循環:奇怪的printf()在while循環中的行爲

#include <ctype.h> 
#include <stdio.h> 

int main(){ 
    int x = 0; 

    while (x != 'q'){ 

    printf("\nEnter a letter:"); 

    x=getchar(); 
    printf("%c\n", x); 
    if(isalpha(x)) 
     printf("You entered a letter of the alphabet\n"); 
    if(isdigit(x)) 
     printf("You entered the digit %c\n", x); 
    } 
    return 0; 
} 

代碼的Debian的擠壓輸出( gcc版本4.4.5(Debian的4.4.5-8))是:

Enter a letter:1 
1 
You entered the digit 1 

Enter a letter: // why is the first one appearing ??? 


Enter a letter:2 
2 
You entered the digit 2 
+0

「回車」鍵產生另一個字符。讓你的循環無條件地打印char值,你會看到。你爲什麼認爲「printf表現得很奇怪」? –

回答

5

第一個讀取你擊中後1(行結束符輸入將保持在輸入緩衝器)時輸入的行終止符。

您可以通過添加一個else分支驗證這一點:

#include <ctype.h> 
#include <stdio.h> 

int main() 
{ 
    int x = 0; 
    while (x != 'q') 
    { 
    printf("\nEnter a letter:"); 
    x = getchar(); 
    printf("%c\n", x); 
    if(isalpha(x)) 
     printf("You entered a letter of the alphabet\n"); 
    else if(isdigit(x)) 
     printf("You entered the digit %c\n", x); 
    else 
     printf("Neither letter, nor digit: %02X\n", x); 
    } 
    return 0; 
} 

輸出:

Enter a letter:1 
1 
You entered the digit 1 

Enter a letter: 

Neither letter, nor digit: 0A 

Enter a letter:2 

字節0A是換行符。

+0

好的,我明白了。那麼,應該如何從std中讀取一個字符? scanf(「%s」,x)不能控制多個字母... – Oz123

+0

我會使用scanf,並分析我得到的字符串。如果它不是單個字符(strlen(x)!= 1),那麼我會打印一條錯誤消息,並再次輸入「輸入一個字母:」。如果你想讀一個整數,這種方法也適用。在這種情況下,安全的方法是讀取一個字符串,並嘗試將其轉換爲整數(atoi)。 – kol

1

通過循環第二次,getchar()得到在輸入第一個字符後輸入

你可以做類似

while ((c = getchar()) != EOF && c != '\n') {} /* eat the rest of the line */ 

擺脫一切直至幷包括下一得到一個字符後,並要求另一前輸入

+0

嗯...我不明白你的解決方案。我確實吃了輸入Enter引起的「\ n」,但它會導致程序退出循環。 – Oz123

+0

此作品,解釋了您的建議: while(c!='q')printf(「\ n輸入一個字母:」); 而((C =的getchar())!= EOF &&!C = '\ n' &&!C = 'Q'){}/*吃線的*/ 其餘} – Oz123

0

如果你想檢查字符,你輸入一個稍微先進的技術將是改變標準輸入的行爲原始模式。然後只要用戶點擊一個字符你得到你的變量。 Check this for some start

0

使用CTRL + D可以獲得換行符的功能,而不會產生副作用。