Portable end of line

Andrew picture Andrew · Mar 26, 2010 · Viewed 19.5k times · Source

is there any way to automatically use correct EOL character depending on the OS used?

I was thinking of something like std::eol?

I know that it is very easy to use preprocessor directives but curious if that is already available.

What I am interested in is that I usually have some messages in my applications that I combine later into a single string and I want to have them separated with a EOL. I know that I could use std::stringstream << endl but it seems to be an overkill sometimes instead of a regular append.

Answer

Potatoswatter picture Potatoswatter · Mar 26, 2010

std::endl is defined to do nothing besides write '\n' to the stream and flush it (§27.6.2.7). Flushing is defined to do nothing for a stringstream, so you're left with a pretty way of saying mystringstream << '\n'. The standard library implementation on your OS converts \n appropriately, so that's not your concern.

Thus endl is already the ultimate in performance and portability, and the only other thing you could want is << '\n' if you are trying to efficiently write to a file (not a stringstream). Well, << '\n' does also eliminate the pointless virtual call to stringbuf::flush. Unless profiling shows that empty function call to be taking time, don't think about it.