unix/linux编程实践教程----fflush函数有什么作用

fflush函数有什么作用?

        先来复习一个简单单词吧:

flush(注意只有一个f):冲洗,冲刷,冲掉。  例句:I flushed the toilet and went back to work again.


      下面,我们来看看一个简单的函数:fflush(file flush,注意有两个f), 先来看一个简单的程序:

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     char c;  
  5.     scanf("%c", &c);  
  6.     printf("%d\n", c);  
  7.   
  8.     scanf("%c", &c);  
  9.     printf("%d\n", c);  
  10.       
  11.     return 0;  
  12.   
  13. }  
       运行这个程序,输入1, 并按enter键,结果为:

49
10
     

      不用吃惊,这个结果很正常的,字符1对应的ASCII值刚好为49, enter键对应的ASCII值为10, 所以就有这样的结果呢。可以看出,第二个scanf函数执行了,并从缓冲区中得到了值(其实,这个值不是我们想要的),那么我们如何把缓冲区这个“马桶”里面的值冲掉呢?用fflush函数就可以了。如下:

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     char c;  
  5.     scanf("%c", &c);  
  6.     printf("%d\n", c);  
  7.   
  8.     fflush(stdin); // 冲掉“马桶”中的无用值  
  9.     scanf("%c", &c);  
  10.     printf("%d\n", c);  
  11.       
  12.     return 0;  
  13.   
  14. }  
      这样,就不会显示10了。


      下面,我们来看MSDN(2008)的一个例子(MSDN上给的程序当然是对的啊):

[cpp]  view plain copy
  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. }  

      要是不信那个邪,你把上面程序中的fflush那一行注释掉,运行一下程序,你就知道有什么后果了。从而,你也就懂了fflush的作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值