Advertisement

endl and \n

Started by August 25, 2002 11:09 AM
5 comments, last by NeonCheese 22 years ago
Is there a difference between endl and \n? I''m on the fifth chapter of my first C++ book, and I''ve yet to find anything that states whether there is or is not. Any help would be greatly appreciated. Thanks.
yes there''s a difference..
now if your question is actually "do they achieve
the same effect" then the answer is yes.

endl and ''\n'' are used in different ways.

ie-
cout << "blah" << endl;
and
cout << "blah\n";

-eldee
;another space monkey;
[ Forced Evolution Studios ]

::evolve::

-eldee;another space monkey;[ Forced Evolution Studios ]
Advertisement
Just what I was looking for. Thanks!
endl will cause the stream to be flushed, but \n will not.


Kami no Itte ga ore ni zettai naru!
神はサイコロを振らない!
\n is the newline character, whereas std::endl is the endline stream manipulator. If/when you use endl it will flush the output buffer as well as add a newline.

cout << "Stuff";
cout << " more stuff";
//that text is not gauranteed to be displayed on the screen yet
cout << endl;
//now it is
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Yes, they are quite different. First some explanation of ostream is required. Writing to stdout or whatever your output is can be a fairly slow process, especially if you''re writing to a disk of any kind. The solution is to use buffered output. ostream has a buffer of characters to write to the output. When this buffer is full, they are written, and the buffer is flushed. This is a lot faster than writing one character at a time. If you want to make sure your text is printed to the screen right after you send it to cout (and not waiting for the buffer to fill), you call the method flush(). Now, endl actually does two things. First it signals the end of the line and puts a newline character (''\n'') into the buffer, then it flushes the buffer.

So as far as usage goes, if you are writing out a big block of text, don''t use endl until the end of all that. If you use it every time you want to end a line, then you lose that built in optimization.
Advertisement
Thanks, everyone. This really helped a lot.

This topic is closed to new replies.

Advertisement