linux 下連續使用多個scanf() 的問題和 fflush(stdin)的變通處理

來源:互聯網
上載者:User

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 供有心人深入研究吧。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.