2012-04-27 53 views
1

我正在使用getchar()來讀取字符並將它們放在一個表上,以及scanf以獲得一個整數。scanf獲取先前執行的getchar的輸入()

scanf()的問題在於它不會等待用戶輸入,而是使用getchar()從緩衝區中讀取上一行給出的最後一個字符。

我試過sscanf,fflush(stdin);等等,但我仍然得到相同的行爲。

#include <stdio.h> 
#include <stdlib.h> 


main() 
{ 
    int i, choice, tmp_day, tmp_month; 
    char name[5]; 

    printf("insert choice(1-3):\n"); 
    scanf("%d",&choice); 


    printf("name: "); 
    for (i=0;i<5;i++) name[i]=getchar(); 

    name[5] = '\0' ; 

    printf("day (1-31): "); 

    scanf("%d",&tmp_day); 

    printf("month (1-12): "); 

    scanf("%d",&tmp_month); 

    printf("\n%d %d", tmp_day, tmp_month); 

} 

任何想法?

在此先感謝。

+0

char name [5]; - >字符名稱[6];索引0..5 =大小是6 – BLUEPIXY 2012-04-27 12:17:59

回答

0

每個之後SCANF使用以下語句:

fflush(stdin); 
+0

你的意思是'fflush(stdin);'? – Jack 2012-04-27 02:49:08

+0

mea culpa,一個錯字:) – Satya 2012-04-27 02:49:54

+0

不只是一個錯字,未定義的行爲。 – 2015-11-14 14:38:52

1

詳細討論有關fflush(stdin)這不一定便攜。

http://c-faq.com/stdio/gets_flush2.html 
+0

謝謝,但這還不夠。他建議使用fgets和sscanf,但fgets的\ n字符沒有被消耗,仍然存在問題。所以我最後把它和定製的cleanBuffer結合起來(使用while((c = getchar())!='\ n'&& c!= EOF)) – Chris 2012-04-29 01:07:34

+0

似乎最好的組合是getline和sscanf。如http://crasseux.com/books/ctutorial/fgets.html所述,fgets已棄用 – Chris 2012-04-29 02:47:17

+0

gets實際上不再是C11標準的一部分。 fgets()是。所以我懷疑你的意思是這個過時了。我喜歡認爲這是非法的。 http://en.wikipedia.org/wiki/C_file_input/output – 2012-04-30 03:00:16