std::endl question

K

keith

Does anyone know the rationale for flushing the output buffer after a
std::endl? It makes for very inefficient writting to a file...
 
M

Maxim Yegorushkin

Does anyone know the rationale for flushing the output buffer after a
std::endl?

The rationale is it to output a newline symbol and flush the stream.
It makes for very inefficient writting to a file...

Use plain '\n' if you don't need flushing.
 
L

Leandro Melo

The rationale is it to output a newline symbol and flush the stream.


Use plain '\n' if you don't need flushing.

Or just write your own myendl manipulator:

template <class charT, class traits>
inline
std::basic_ostream<charT, traits>&
myendl(std::basic_ostream<charT, traits>& os)
{
os.put(os.widen('\n'));
return os;
}
 
J

Jim Langston

keith said:
Does anyone know the rationale for flushing the output buffer after a
std::endl? It makes for very inefficient writting to a file...

There are situations where it is desirable to flush the output buffer. One
instance is a program I was trying to debug and I put std::cout << "Got
here\n"; type messages all over but I couldn't figure out why the heck it
wasn't showing some output it should, til I realized that the program was
crashing and so the buffers weren't being flushed before the abend so I
never saw the output. Replacing the \n's with std::endl fixed the problem
and I saw all output.

Usually, however, you probably don't need to flush the buffer on every
newline.
 
J

James Kanze

Does anyone know the rationale for flushing the output buffer
after a std::endl?

The basic rationale is to ensure that the output is actually
output. It's the closest thing C++ has to line buffering.
It makes for very inefficient writting to a file...

That depends on what you're doing. Most of the time, it's not a
problem.
 
J

Juha Nieminen

keith said:
Does anyone know the rationale for flushing the output buffer after a
std::endl? It makes for very inefficient writting to a file...

Think about it like this:

If you want to output a newline without flushing, you can use "\n".

If you want to flush after the newline, you would have to write
"\n" << std::flush;

However, you don't have to do that, as you can use std::endl.

There are situations where you want to flush after each newline, so it
becomes handy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top