一、三點說明
1、用戶輸入的字符,會以ASCII碼形式存儲在鍵盤緩沖區;
2、每調用一次scanf函數,就從鍵盤緩沖區讀走一個字符,相當於清除緩沖區;
3、若用戶一次輸入n個字符,則前n次調用scanf函數都不需要用戶再次輸入,直到把緩沖區的數據全部讀取(清除)干凈
4、調用scanf()函數時,用戶最后輸入的回車也會儲存在鍵盤緩沖區;(見程序示例2)
二、程序示例1
1 # include <stdio.h>
2
3 int main() 4 { 5 char ch; 6 while (1) 7 { 8 scanf("%c", &ch); 9
10 switch(ch) 11 { 12 case '1': 13 printf("haha\n"); 14 break; 15 case '2': 16 printf("cccccc\n"); 17 // fflush(stdin); //清除緩沖區
18 break; 19 case '3': 20 printf("555\n"); 21 break; 22 case 'e': 23 return 0; 24 default: 25 return 0; 26 } 27 } 28
29
30
31 return 0; 32 } 33
34 /*
35 程序在VC++6.0中的顯示結果是: 36 1235r 37 haha 38 cccccc 39 555
程序示例2
1 # include <stdio.h> 2 3 int main() 4 { 5 char c; 6 scanf("%c", &c); 7 printf("%d\n", c); 8 9 scanf("%c", &c); 10 printf("%d\n", c); 11 12 return 0; 13 } 14 15 /* 16 程序在VC++6.0中的顯示結果是: 17 1 18 49 19 10 20 */
上例中因為1對應的ASCII碼是49,回車鍵對應的ASCII碼是10,故有以上輸出;
第二個scanf從緩沖區讀入了“回車”,顯然這是我們不願要的,如果要想清除這個垃圾值,只需要在第8行添加語句fflush(stdin)
程序示例3
1 #include <stdio.h> 2 #include <conio.h> 3 4 void main( void ) 5 { 6 int integer; 7 char string[81]; 8 9 /* Read each word as a string. */ 10 printf( "Enter a sentence of four words with scanf: " ); 11 for( integer = 0; integer < 4; integer++ ) 12 { 13 scanf( "%s", string ); 14 printf( "%s\n", string ); 15 } 16 17 /* You must flush the input buffer before using gets. */ 18 fflush( stdin ); 19 printf( "Enter the same sentence with gets: " ); 20 gets( string ); 21 printf( "%s\n", string ); 22 }
三、清除緩沖區的幾種方法
我們使用多個scanf()的時候,如果輸入緩沖區還有數據的話,那么scanf()就不會詢問用戶輸入,而是直接就將輸入緩沖區的內容拿出來用了,這就導致了前面的錯誤影響到后面的內容,為了隔離這種問題,需要通過各種方法將輸入緩沖區的內容讀出來(清除)
1、fflush(stdin)
在程序17行如果插入代碼,依然輸入1235r,則輸出為 haha cccccc
此種方法對vc可以,但對xcode和linux不適用
2、while+getchar
while (ch=getchar() != '\n' && ch != 'EOF'),直到讀取到緩沖區的換行或者空值
四、關於scanf函數接受鍵盤的細節
程序示例1
1 #include <stdio.h> 2 3 int main() 4 { 5 int a = 0, b =0; 6 char d = 'a', e ='a'; 7 scanf("%d",&a); //輸入字符a到緩存,跳過接受,a=0 8 scanf("%d",&b); //輸入字符a到緩存,跳過接受,b=0 9 scanf("%c",&d); //輸入字符a到緩存,接受,d=a 10 scanf("%c",&e); //e接受換行符,ASCII為10 11 printf("%d,%d,%c,%d\n",a,b,d,e); 12 return 0; 13 } 14 15 /* 16 程序在VC++6.0中的顯示結果是: 17 a 18 0,0,a,10 19 */