Search code examples
c++language-lawyernewlineiostreamflush

Does std::cout guarantee to print a string if it doesn't end with a newline?


I've heard that the following program isn't guaranteed to print the string on every platform and to actually do it you need to add \n to the end or flush the buffer by other means. Is that true or does the standard guarantee the expected output anyway?

#include <iostream>

int main() {
    std::cout << "Hello, world!";
}

Solution

  • [ios.init]/1 The class Init describes an object whose construction ensures the construction of the eight objects declared in <iostream> (29.4) that associate file stream buffers with the standard C streams provided for by the functions declared in <cstdio> (29.12.1).

    [ios.init]/3
    Init();
    Effects: Constructs and initializes the objects cin, cout, cerr, clog, wcin, wcout, wcerr, and wclog if they have not already been constructed and initialized.

    [ios.init]/4
    ~Init();
    Effects: If there are no other instances of the class still in existence, calls cout.flush(), cerr.flush(), clog.flush(), wcout.flush(), wcerr.flush(), wclog.flush().

    So therefore, std::cout.flush() would be called as part of the program's normal termination sequence, by the destructor of the same object (sometimes known as nifty counter) that ensured std::cout was initialized in the first place.