使用sleep()时C中puts()和printf()之间的区别 [英] Difference between puts() and printf() in C while using sleep()

查看:165
本文介绍了使用sleep()时C中puts()和printf()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在使用sleep()函数时puts()和printf()函数之间的区别.

I was wondering the difference between puts() and printf() functions while using sleep() function.

这是我的代码(用C语言):

Here is my code(In C language):

printf("hello, world");
sleep(1);
printf("Good, bye!");

在编译并运行该程序之后,它似乎会首先进入睡眠状态,然后打印"hello,worldGood,再见!"

After compiling and running the program, it seems that it will sleep first and then print "hello, worldGood, bye!"

但是,如果使用puts()而不是printf(),它将打印"hello,world",然后进入睡眠状态,最后打印"Good,bye".

However, if using puts() instead of printf(), it will print "hello, world" then sleep, and finally print "Good, bye".

puts("hello, world");
sleep(1);
puts("Good, bye!);

推荐答案

这是因为存在缓冲-默认情况下,标准输出缓冲到每一行. printf()不包含换行符,因此不会刷新输出. puts()包含换行符,因此将刷新输出.

This is because of buffering - by default, standard out buffers up to each new line. printf() does not include a newline, so output isn't flushed. puts() includes a newline, so output is flushed.

您可以通过插入换行符来使printf()刷新:

You can cause printf() to flush by putting a newline:

printf("hello, world\n");

或直接致电fflush():

fflush(stdout);

有关缓冲的更多信息,请参见 setbuf()的手册页:

For more about buffering, see the man page for setbuf():

The three types of buffering available are unbuffered, block buffered, and
   line buffered.  When an output stream is unbuffered, information appears on
   the destination file or terminal as soon as written; when it is block 
   buffered many characters are saved up and written as a block; when it 
   is line buffered characters are saved up until a newline is output or input
   is read from any stream attached to a terminal device (typically stdin).
   ....
   If a stream refers to a terminal (as stdout normally does) it is 
   line buffered. 
   ....
   The standard error stream stderr is always unbuffered by default.

这篇关于使用sleep()时C中puts()和printf()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆