您的位置:首页 > 运维架构 > Linux

linux 下连续使用多个scanf() 的问题和 fflush(stdin)的变通处理

2014-03-25 14:52 501 查看
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 供有心人深入研究吧。

转载:http://blog.csdn.net/johnphan/article/details/5337509
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: