Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I stop std::cout flushing on "\n"?

According to to this post std::cout will automatically flush on \n 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?

like image 342
pauldoo Avatar asked Apr 28 '09 08:04

pauldoo


People also ask

How do you stop cout without a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.

Does cout flush automatically?

It is an implementation detail, one that invariably depends on whether output is redirected. If it is not then flushing is automatic for the obvious reason, you expect to immediately see whatever you cout. Most CRTs have an isatty() helper function that is used to determine whether automatic flushing is required.

Does newline character flush the buffer?

Yes, when the file stream is closed at the (normal) end of the program, pending output will be flushed. It'll also be flushed when the buffer is full.

Should I use std :: endl or \n?

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n' . If you do (for example, if you want to get all the output, and the program is unstable), use std::endl .


1 Answers

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.

like image 112
Matt Whitlock Avatar answered Sep 23 '22 07:09

Matt Whitlock