2012-09-07 39 views
1

我在運行以下代碼時遇到了一些問題。如果我向scanf方法饋送數組a提供超過五個字符的輸入,則其餘字符將進入數組b,我不會再提供輸入。我嘗試使用fflush(),但它沒有幫助。怎麼回事,我該如何解決?用於溢出輸入的scanf行爲

#include<stdio.h> 

int main() 
{ 
char a[6]; 
char b[20]; 

printf("Enter any string :\n"); 
scanf("%5s",a); 

printf("%s\n",a); 

fflush(stdin); 

scanf("%s",b); 
printf("%s\n",b); 

return 0; 
} 
+0

也許dupplicate這個問題http://stackoverflow.com/questions/3437656/my-program-is-not-asking-for-the-operator-the-second-time –

回答

2

您不應該使用fflush(stdin)清除輸入緩衝區及其未定義的行爲,只有Microsoft-CRT支持這一點。

#include<stdio.h> 

int main() 
{ 
int c; 
char a[6]; 
char b[20]; 

printf("Enter any string :\n"); 
scanf("%5s",a); 

printf("%s\n",a); 

while((c=getchar())!=EOF && c!='\n'); 

scanf("%19s",b); 
printf("%s\n",b); 

return 0; 
}