Linux 和 Windows 上的 printf [英] printf on Linux vs Windows

查看:113
本文介绍了Linux 和 Windows 上的 printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一些C代码:

int i;
printf("This text is printed\nThis text is not until the for loop end.");
for (i = 5; i > 0; i--)
{
    printf("%d", i);
    sleep(1);
}

为什么 '\n' 之后的其余文本没有在 for 循环开始之前打印?甚至 for 循环中的 printf 也只在循环结束后打印.如果我将 '\n' 放在文本的末尾,它会打印出来,但我不想换行.

Why is the rest of the text after the '\n' not printed before the for loop start? Even the printf inside the for loop is only printed after the loop end. If I put a '\n' at the end of the text, it prints, but I do not want a new line.

这只发生在 Linux 上,而不发生在 Windows 上(只是将 sleep(1) 更改为 Sleep(1000) 并添加了 windows.h).

This only happens on Linux and not on Windows (just changed sleep(1) to Sleep(1000) and added windows.h).

推荐答案

它是由输出缓冲引起的.当您调用 printf 时,不会立即打印输出.它被写入缓冲区以在将来某个时候输出.通常 \n 字符会导致缓冲区自动刷新.您也可以手动刷新 stdout 缓冲区:

It's caused by output buffering. When you call printf, the output isn't printed immediately. It is written to a buffer to be output sometime in the future. Usually a \n character causes the buffer to be flushed automatically. You can also flush the stdout buffer manually:

printf("This text is printed\nThis text is not until the for loop end.");
fflush(stdout);

这篇关于Linux 和 Windows 上的 printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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