printf 不立即显示的问题解决方案,fflush

  fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃

但是fflush(stdin)在linux里并没有实现,这是要通过,while ( (ch=getchar()) != '/n' && ch != EOF );来实现。

 

  fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上

 

 the standard says that stdout is initially fully buffered if the output device can be determined to be a non-interactive one.

It means that, if you redirect stdout to a file, it won't flush on newline. If you want to try and force it to line-buffered, use setbuf or setvbuf .

The relevant part of C99, 7.19.3 Files, paragraph 7 , states:

At program startup, three text streams are predefined and need not be opened explicitly - standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

Just keep in mind section 5.1.2.3/6 :

What constitutes an interactive device is implementation-defined.

 

以下转载自:http://blogold.chinaunix.net/u3/117440/showart_2328478.html

 

 

以下程序只是为了在终端上不断连续输出- > 而已,但是在没有加fflush之前发现根本无法向屏幕打印任何内容。为什么以前从来没有发现 printf的这种特性呢?后来想到,以前在用printf时多收情况下都会在字符串尾部加一个/n。或者没有加/n, 但 是你的程序不是一个dead loop,便也不会牵扯到问题,因为就算执行printf后只是将内容送到缓冲区,但是你到程序结束里,程序结束便会导致缓冲区刷新,你便看到你到屏幕上 有你期望到东西出现了。所以我最后得到一个这样到结论:printf会把东西送到缓冲区,而如果缓冲区不刷新到话,你便不会在屏幕上看到东西,而能导致缓 冲区刷新到情况有这些:1 强制刷新 fflush;2,放到缓冲区到内容中包含/n /r ;3,缓冲区已满;4,需要从缓冲区拿东西到时候,如执行scanf;
但是这些问题在vc中都没有出现,所以这时编译器相关的!

# include < stdio. h>
# include < unistd. h> //for sleep()


int main( void )
{
    printf ( "/nstart the dead loop/n" ) ;
    while ( 1)
    {
        printf ( "/b->" ) ;
        fflush ( stdout ) ; //刷新输出缓冲区,如果不做这个动作,上边的输出便不会显示到屏幕上,除非其中有换行操作或者缓冲区,这也许就是所谓到终端行规程吧。

        usleep ( 100000) ;
    }
    return 1;
}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值