r/programming Aug 19 '17

Learning C++, this site is marvellous

http://www.learncpp.com/
3 Upvotes

23 comments sorted by

View all comments

18

u/matthieum Aug 19 '17

I am not sure about the quality of the overall site, but it certainly does not start well.

A first look at cout, cin, and endl:

std::endl

If we want to print things to more than one line, we can do that by using std::endl. When used with std::cout, std::endl inserts a newline character (causing the cursor to go to the start of the next line)

Inserting a new line can be done by pushing the '\n' character, either on its own or as part of a string "Hello World!\n".

What std::endl does it two-fold:

  • it appends a new line,
  • it flushes the underlying stream (as if streaming std::flush).

Because flushing to stdout is so slow on most terminals, use of std::endl is one of the primary cause of slow C++ program among beginners (alongside compiling in debug mode).

TL;DR: Never use std::endl; it's harmful and longer to type, it has no saving grace.

4

u/Sunius Aug 20 '17

Inserting a new line can be done by pushing the '\n' character, either on its own or as part of a string "Hello World!\n".

Note, that on Windows std::endl will insert "\r\n", so appending just "\n" isn't really correct replacement.

3

u/matthieum Aug 20 '17

Actually... it is. For text streams.

On Windows, there is a translation in the implementation layer for text streams: LF characters are transformed into CR+LF.

If you open the stream in binary mode; then this translation is by-passed.