hi-jin
hi-jin

Reputation: 13

Why some examples are using "endl" instead of "\n"?

Why some examples are using "endl" instead of "\n"?

I heard that processing time of "endl" is longer than "\n" because "endl" has some flushing process.

But, there are so many examples using "endl" on the internet.

I wanna know why they're using "endl" which thought to be inefficient.

Sorry for the awkward English...... Thanks

Upvotes: 1

Views: 418

Answers (2)

Deduplicator
Deduplicator

Reputation: 45654

  1. Many think that << std::endl is different from << '\n' << std::flush, as it would insert the right end-line markers.
    That is obviously nonsense.

  2. Others do not understand that std::cin and std::cout are tied together, thus the latter is flushed when the former wants to read.

  3. Still others have never heard of std::cerr, and thus misdirect logging to std::cout.
    If you use the wrong tool, bludgeoning it into behaving as you want instead of taking a step back and recognizing you want a hammer and not a screwdriver is distressingly common.

  4. If you really want, maybe because your program is especially flaky and you are programming by trial and error (which makes it unlikely your code will actually be correct, instead of just seem to "work" at the end), you can easily make std::cout unbuffered too.
    No need to get into even more bad habits.

     std::cout << std::unitbuf;
    

Upvotes: 2

lubgr
lubgr

Reputation: 38267

Oftentimes, direct usage of std::cout is something not meant for production code, where it's usually preferred to use some kind of logging facility (for writing to a file instead of standard stream etc.). Within such logging library, you would want to take care you only flush when desired, but for some ad hoc, debugging-like output of stuff, the performance implications of std::endl don't really matter and it's more important to immediately see the desired output.

Upvotes: 1

Related Questions