Others have already suggested using endl . Although this is (not necessarily) bad, using endl clears the stream buffer along with writing a new line. Unlike one of the answers you received, using endl does not help (in general) when translating a new line to any sequence of characters that the platform usually uses to signal the end of a line. Using newline guaranteed to be exactly equivalent to stream << "\n" << flush;" . Newlines are translated to" \ r "or" \ n "or" \ r \ n "or whatever the platform prefers, runs on another level, and newline has nothing to do with it.
However, flush , what it does, can (and often will) slow down your I / O, sometimes by a pretty significant margin. While you are writing a few lines (for example, a couple of hundred characters), this probably does not matter at all. However, if you write a large file, using endl instead of "\n" can lead to 10x slowdowns (in fact, I would say that most of the idea that iostreams are slow stems directly with endl ).
Not to say, there was never a reason to use endl. flush ensures that everything written in the stream is immediately flushed from the standard library buffer and sent to the OS. If you want to provide an immediate display, endl may be useful. Similarly, if you are logging, and it is important that your log always reflects the latest known state of the program, endl can be (extremely) useful to ensure that what you write is actually logged and not lost in the buffer when / if the application crashes.
Thus, endl makes sense from time to time, but probably in 95% of the cases when it was used, it is really inappropriate (for example, it is unlikely that it will do anything useful in any of the answers to this question).
source share