Akshat.saxena21's blog

By Akshat.saxena21, history, 4 years ago, In English,

Though there is no difference between the working of endl and \n. Both work as a ‘enter Key’. But there is a huge difference between their working mechanism. Endl flushes the output buffer and ‘\n’ doesn’t. if you want the buffer flushed frequently, use ‘\n’. if you do, use endl.

Endl is actually slower because it forces a flush, which actually unnecessary. You would need to force a flush right before prompting the user for input from cin, but not when writing a million lines of output. Write ‘\n ’ instead of endl. **** The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

The difference can be illustrated by the following: std::cout << std::endl; is equivalent to std::cout << '\n' << std::flush; So, • Use std::endl If you want to force an immediate flush to the output. if you are in a command line app and want to guarantee that the user can see the output immediately. • Use \n if you are in a worried about performance (which is probably not the case if you are using the << operator). I use \n on most lines. Then use std::endl at the end of a paragraph (but that is habit it is usually not necessary). Contrary to other claims, the \n character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin and std::cout being special but still files (or file-like)).

Read more »

  • Vote: I like it
  • +17
  • Vote: I do not like it