为什么在 c++ 中使用 ios::sync_with_stdio(false) 后在 cout 之前执行 printf

Why printf is executed before cout after using ios::sync_with_stdio(false) in c++?

本文关键字:false 后在 cout printf 执行 with c++ 为什么 sync ios stdio      更新时间:2023-10-16
#include <iostream>
#include <stdio.h>

int main () {
std::ios::sync_with_stdio(false);
std::cout << "hi from c++n";
printf("hi from cn");
return 0;
}

删除 std::endl 并将 放在 cout 语句中后,输出更改为以下内容:

hi from c
hi from c++

这是一个缓冲问题。

默认情况下,当标准输出连接到终端时,stdout行缓冲的,这意味着缓冲区被刷新,输出实际上以换行符写入终端。

当 C stdio 与C++标准流断开连接时,std::cout完全缓冲的,这意味着输出实际上是在显式刷新时写入的(例如使用std::flushstd::endl操纵器),或者缓冲区是否已满。

Cstdout和C++std::cout使用的两个缓冲区不同且未连接。

当程序退出时,也会刷新缓冲区。


程序中发生的情况是,由于字符串中的尾随换行符,带有printf的输出会立即刷新。但是,只有当程序退出时,才会刷新std::cout的输出。