为什么输出在睡眠后没有换行符?
Why does the output comes after sleep without newline?
我正在使用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 buffered
,fully buffered
与文件一起使用时,字符串将存储在缓冲区中,可以通过输入新行或缓冲区填充或程序终止时
刷新您还可以使用setvbuf
覆盖缓冲区模式,如下所示
setvbuf(stdout, NULL, _IONBUF, 1024);
printf("a");
它将在没有缓冲的情况下打印a
,请查看使用setvbuf
的 https://www.tutorialspoint.com/c_standard_library/c_function_setvbuf.htm
还可以查看不同类型的流缓冲。
希望这对你有帮助。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 流:CSV 文件中的换行符
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- Clang-格式:在多行语句之后的换行符上打开大括号
- 在输出流中插入换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- QProcess::readAllStandardOutput() 和换行符
- 如果有换行符,clang 格式不会附加大括号
- 提取后返回换行符的C++istream.get()
- 为什么输出在睡眠后没有换行符?
- 在命令提示符下看到换行符,但在文件输出中可以看到 相同的字符串
- 为什么 std::cout 在我的输出中添加返回或换行符
- 输出到文本文件时C++换行符
- 简单的字符串输出不符合预期(出现换行符)
- 输出换行符的最有效方法
- c++输出debugstringw与换行符
- 程序转到换行符,屏幕上没有任何输出
- 为什么此代码输出文字"n"而不是换行符?