2013-06-04 64 views
1

我試圖讓用戶輸入一個數字多少次(併爲每個數字創建一個鏈接列表節點)。scanf/getchar只能通過循環第一次正常工作?

但是,我試過清除字符輸入緩衝區的多種方法,但無濟於事。奇怪的是,代碼將執行一次,但不會正確執行第二個。

例如,用下面的代碼,終端讀取:

would you like to enter an integer? 
y 
Enter an integer: 4 
would you like to enter an integer? 
y 
**program terminates** 

我用​​時之前我不會甚至能夠在最後一行輸入「Y」。它剛剛結束。

struct node *read_numbers(void){ 
    struct node *first = NULL; 
    int n; char yesno; 
    yesno = 'y'; 
    while(yesno == 'y'){ 
     printf("Would you like enter an integer ((y) for yes/(n) for no):\n"); 
     yesno = getchar(); 
     while(getchar() != '\n'); 
     if(yesno == 'y'){ 
      printf("Enter an Integer:"); 
      scanf(" %d", &n); 
      first = add_to_list(first, n); 
      } else { 
       return first; 
       } 
     } // end while 
    } 

我讀到了字符輸入和緩衝區,並且據說getchar()方法應該可以工作。我用錯了嗎?我也在「%c」之前和之後嘗試使用scanf()和額外的空格,但無濟於事。

回答

3

您需要在scanf後消化換行符。你可以做你在上面的代碼做什麼:

scanf(" %d", &n); 
while(getchar() != '\n'); 
first = add_to_list(first, n); 
+0

工作!爲什麼我需要'while(getchar()!='\ n');''scanf()'之後'if,呃...我正在使用'scanf()'(vs'getchar()')? – LazerSharks

+0

@Gnuey,因爲scanf將掃描字符串直到找到空白字符,但該字符將留在讀取緩衝區中。 getchar()從該緩衝區中讀取數據,以便它讀取你的換行符並離開while循環。 scanf笨重。大多數人使用fgets + sscanf來做你的代碼 – Guillaume

+0

啊,我明白了。謝謝! – LazerSharks

1

getchar是從標準輸入獲取數據,while(getchar() != '\n');就像清除標準輸入緩衝區。 所以下面的代碼可以正常工作

2

我可以建議您使用fgetsgetcharscanf一個更安全的替代?

正如您已經注意到的那樣,這些函數可以緩存換行符,並將它傳遞給從標準輸入讀取的下一個函數。

With fgets您可以將輸入存儲在字符數組中,並避免出現此類問題。另外,如果輸入僅包含換行符,您仍然可以輕鬆檢查:

char user_input[10] = ""; 

printf("Would you like enter an integer ((y) for yes/(n) for no):\n"); 

/* get input or quit if only newline is entered, we only check the first char */ 
while(fgets(user_input, 3, stdin)[0] != '\n') 
{ 
    /* check if the first char is 'y', quicker to do than using strcmp */ 
    if(user_input[0] == 'y') 
    { 
     int input = 0; 

     printf("Enter an Integer: "); 

     fgets(user_input, 5, stdin); /* get input again */ 

     input = atoi(user_input); /* convert to int */ 

     printf("Your integer is %d\n", input); 

     printf("Would you like to go again? y/n:\n"); 
    } 
    else 
    { 
     return printf("No input there.\n"); 
    } 
} 
+0

啊,我明白了!這確實工作得很好。 Upvoted,謝謝。 – LazerSharks

+0

高興地幫助:) – Nobilis

相關問題