Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

c++ - Can I stop std::cout flushing on " "?

According to to this post std::cout will automatically flush on when it is attached to an interactive device (e.g. a terminal window). Otherwise (e.g. when being piped to a file) it will act fully buffered and will only flush on .flush() or std::endl.

Is there a way to override this behaviour in Microsoft Visual C++ so that I can select whether I want fully buffered or line buffered mode?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Contrary to anon's (Apr 28 '09) answer, this behavior has nothing to do with the operating system or "console software."

C++'s <iostream> streams are designed to be interoperable with C's <stdio.h> streams. The goal is to allow uses of std::cout to be intermixed with uses of printf/puts. To achieve this, std::cout's streambuf is implemented atop C's stdout stream. It is actually C's stdout that is line-buffered when the standard output is attached to a terminal device.

You can call std::ios_base::sync_with_stdio(false) (before your program uses any of C++'s standard I/O streams) to tell the C++ streams library to communicate directly with the underlying file descriptors rather than layering atop C's streams library. This avoids C's stdout stream entirely and speeds up C++'s I/O streams at the cost of the two libraries no longer mixing well.

An alternative is to unconditionally set stdout to fully buffered by calling std::setvbuf(stdout,?nullptr,?_IOFBF,?BUFSIZ). Then, even though std::cout is still writing through stdout, you will not have stdout flushing after every newline.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...