为什么输出在睡眠后没有换行符?

Why does the output comes after sleep without newline?

本文关键字:换行符 输出 为什么      更新时间:2023-10-16

我正在使用gcc 7.3和g ++ 7.3。GCC 和 G++ 会出错。例如

#include <stdio.h>
#include <unistd.h>
int main() {
printf("a");
sleep(1);
return 0;
}

等待 1 秒后打印"a",但当我使用printf("an");时它可以正常工作。C++上也一样。例如

#include <iostream>
#include <unistd.h>
int main() {
std::cout << "a";
sleep(1);
return 0;
}

等待 1 秒后也会打印"a"。但是,当我使用std::cout << "a" << std::endl;时,它可以正常工作。问题是什么以及如何解决?

sleep()就像手动安排一个进程printf()将数据放入流中stdout而不是直接放在监视器上。

printf("a"); /* data is there in stdout , not flushed */ 
sleep(1); /* as soon as sleep(1) statement occurs your process(a.out) jumped to waiting state, so data not gets printed on screen */ 

因此,您应该使用fflush(stdout)或使用n来清除stdout流。

您会看到这种行为,因为 stdout 在与终端一起使用时通常会line bufferedfully buffered与文件一起使用时,字符串将存储在缓冲区中,可以通过输入新行或缓冲区填充或程序终止时

刷新您还可以使用setvbuf覆盖缓冲区模式,如下所示

setvbuf(stdout, NULL, _IONBUF, 1024);
printf("a");

它将在没有缓冲的情况下打印a,请查看使用setvbuf的 https://www.tutorialspoint.com/c_standard_library/c_function_setvbuf.htm

还可以查看不同类型的流缓冲。

希望这对你有帮助。