如何解决为什么 std::nounitbuf 在 MSVC 上不做任何事情?
我正在写一门关于现代 C++ 的课程,想解释刷新操作的工作原理,所以我决定禁用自动刷新,以便仅在 std::cout
被销毁时写入缓冲区。
为此,只有一个标准函数存在,它是操纵器 std::nounitbuf
。
但是,这不适用于 MSVC。
最让我惊讶的是 C 中的替代方法,setvbuf
函数,实际上允许您停用自动刷新。
这让我有点困扰,因为我想教 C++ 而不是 C。
谁能帮帮我?谢谢!
#include <iostream>
#include <thread>
int main()
{
std::cout << std::nounitbuf; // doesn't work (output is two Hello World before the 5 seconds delay)
//setvbuf(stdout,nullptr,_IOFBF,BUFSIZ); // work (output is one Hello World,then another one after the 5 seconds)
std::cout << "Hello World" << std::endl;
std::cout << "Hello World";
std::this_thread::sleep_for(std::chrono::seconds{ 5 });
}
解决方法
来自:https://en.cppreference.com/w/cpp/io/manip/endl
在许多实现中,标准输出是行缓冲的,并且写入
'\n'
无论如何都会导致刷新,除非 std::ios::sync_with_stdio(false)
被处决了。
尝试从输出中删除 std::endl
和 '\n'
,您将获得所需的行为。正如 Marek 所说,std::nounitbuf
是 std::cout
的默认设置。
为什么 std::nounitbuf 什么都不做?
很可能是因为标准 unitbuf
流的 cout
标志默认未设置。 (Standard narrow.stream.objects 要求只应为 cerr
设置)。
有人可以帮我吗?
C++ 与 stdio 流同步(未缓冲)。你写的std::cout << "something"
直接到FILE*
stdout
。当它直行时,stdout
缓冲是最重要的。
禁用与 stdio 流的同步,然后尝试。阅读std::ios::sync_with_stdio。以下对我有用。
#include <iostream>
#include <thread>
int main() {
std::ios::sync_with_stdio(false);
std::cout << "Hello World" << std::endl;
std::cout << "Hello World\n";
std::this_thread::sleep_for(std::chrono::seconds{ 5 });
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。