Question

Before you declare this question as a duplicate of this or that, please consider that I've submitted a problem to the online judge with \n and got WA, and then with std::endl and got AC. So, I need a very specific answer to the point of platform awareness: Is \n really platform aware, and does the runtime really write the correct line ending according to the platform as the answers to the other questions claim? If so, could you please tell me how this happened??

If the answer can be supported by a citation from the standard regarding the platform awareness issue, I'd be really thankful. I've read all the other questions' answers (even the closed ones), so please don't repeat the "flushes the buffer" thing.

Was it helpful?

Solution

From C++11, §27.7.3.8 -

namespace std
{
    template <class charT, class traits>
        basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}

Effects:Calls os.put(os.widen(’\n’)), then os.flush().

Returns:os.

So, from the standard it's clear that endl flushes the output stream buffer, while \n doesn't. Generally you will want to use endl for printing a new line, but you should also keep in mind that every time you do that the output buffer will get flushed too.

About the platform awareness

From the standard it's obvious that both does the exact same thing - printing a new line in the exact same way. So, if one is platform independent, then the other should also be the same. Since I know for sure endl is platform independent, same should be the case for \n.

OTHER TIPS

std::endl is a manipulator which outputs '\n', then flushes the stream. For most casual use, it's what you should be using. When outputting large volumes of data, however, it can result in a significant performance hit, in which case, use '\n'.

EDIT:

With regards to platform awareness: both output exactly the same thing. If the stream was opened in text mode, the '\n' will cause a platform dependent representation of a line ending to occur: 0x0A under Unix, 0x0D, 0x0A under Windows, start a new record under some mainframes, etc. If the stream was opened in binary mode, it will cause a single byte (typically 0x0A, but it actually depends on the basic character encoding used) to be output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top