When to write std:: endl and when '\n'?

There are two ways to write a line feed - std::endl and \n. What's the difference? When to use what?

 11
Author: Abyx, 2015-05-02

2 answers

std::endl implemented as os.put(os.widen(’\n’)); os.flush();. Accordingly, the only difference is that endl causes flush(), and \n does not.

Calling flush() clears the stream buffer, and if executed too often, it can significantly slow down the program.

Also remember that std::endl is not needed where the standard library itself calls cout.flush():

  • at the end of the program
  • when reading from std::cin
  • when writing to std::cerr

Some implementations buffer the output to stdout line by line, and the \n entry itself will call flush.

You can write the buffer explicitly using the std::flush manipulator, for example

std::cout << "Calculating XYZ ... " << std::flush; wait_XYZ(); std::cout << "OK\n";

Links

 16
Author: Abyx, 2015-05-02 10:23:13

It should be remembered that in c++ files themselves are not closed when you exit the program. Maybe they are closed, but only in memory, and the file will not be visible on disk. The previous person correctly said: it depends on what goal you are pursuing. Perhaps you don't need to flush so often, especially in the loop.

Write "@": so that it comes to the mail. I accidentally saw your comment. Essentially: no threads close themselves (at least on disk). You have to specify close() in the object destructor so that the file is on disk. pascal is easier: there you can not specify the closure, when you exit the program, it will close itself.

 -6
Author: Airhand, 2017-12-02 15:30:07