Comparison Between endl and \n in C++

Правка en1, от Akshat.saxena21, 2016-03-13 21:10:18

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)).

Теги c++, endl, escape sequence

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский Akshat.saxena21 2016-03-13 21:10:18 1582 Initial revision (published)