linux 下連續使用多個scanf() 會有問題,執行個體:
while (1)
{
printf("Please input: ");
scanf("%s",pstr) ;
}
這段程式運行會出問題,當一次輸入後,會不停的提示Please input:,程式不會在scanf等待下一次的輸入。
一般資料會說添加fflush函數可解決這個問題:
while (1)
{
printf("Please input: ");
scanf("%s",pstr) ;
fflush(stdin);
}
但是在gcc 版本 4.1.2 20080704 (Red Hat 4.1.2-46)下,fflush函數形同虛設。man fflush有詳細的說明可參考。
網路上有人說,在scanf之後使用一個getcahr()可解決,可是,當時輸入多個字元還是有問題。
while (1)
{
printf("Please input: ");
scanf("%s",pstr) ;
getchar();
}
執行結果:
Please input: 1
Please input: 22
Please input: Please input: 333
Please input: Please input: Please input: 4444
Please input: Please input: Please input: Please input:
添加一個迴圈,問題解決了:
while (1)
{
printf("Please input: ");
scanf("%s",pstr) ;
while ('/n' != getchar() );
}
附一個在網路上查到的另一個解決方案:
#define STR_BUFFSIZE 5
while (1)
{
printf("Please input: ");
scanf("%s",pstr) ;
char buffer[STR_BUFFSIZE];
while( fgets(buffer, STR_BUFFSIZE, stdin) != NULL )
if(buffer[strlen(buffer)-1] == '/n' )
}
結論:Linux下C語言連續多個scanf()這麼不好用,用gets函數代替如何呢?gets函數也有漏洞!(網路搜尋就知道了)
scanf這個現象是如何產生的呢?參考課本是可以有合理的解釋。但還是代碼說明一切。附一個版本scanf()函數的原始碼: http://ftp.gnu.org/gnu/glibc/glibc-2.0.6.tar.gz 供有心人深入研究吧。