what does std::endl represent exactly on each platform?

后端 未结 5 1259
孤独总比滥情好
孤独总比滥情好 2021-01-11 12:01

Thinking about UNIX, Windows and Mac and an output stream (both binary and text),

What does std::endl represent, i.e. ,

相关标签:
5条回答
  • 2021-01-11 12:46

    The C++ standard says that it:

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

    What the '\n' is converted to, if it is converted at all, is down to the stream type it is used on, plus any possible mode the stream may be opened in.

    0 讨论(0)
  • 2021-01-11 12:50

    The code:

    stream << std::endl;
    
    // Is equivalent to:
    
    stream << "\n" << std::flush;
    

    So the question is what is "\n" mapped too.
    On normal streams nothing happens. But for file streams (in text mode) then the "\n" gets mapped to the platfrom end of line sequence. Note: The read converts the platform end of line sequence back to a '\n' when it reads from a file in text mode.

    So if you are using a normal stream nothing happens. If you are using a file stream, just make sure it is opened in binary mode so that no conversion is applied:

    stream << "\r\n"; // <CR><LF>
    
    0 讨论(0)
  • 2021-01-11 12:50

    Use stream << "\r\n" (and open the stream in binary mode). stream << std::endl; is equivalent to stream << "\n" << flush;. The "\n" might be converted to a "\r\n" if the code runs on Windows, but you can't count on it -- at least one Windows compiler converts it to "\n\r". On a Mac, it's likely to be converted to "\r" and on Unix/Linux and most similar systems, it'll be left as just a "\n".

    0 讨论(0)
  • 2021-01-11 12:55

    Looks like your question got munged. Each command ends in []? For an over-the-wire protocol, I'd suggest using a delimiter that doesn't vary by platform. std::endl could resolve to '\r\n' or '\n\r' depending on the platform.

    0 讨论(0)
  • 2021-01-11 13:02

    Quoted from the accepted answer on a related question:

    The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

    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

    In your case, since you specifically want <CR><LF>, you should explicitly use \r\n, and then call std::flush() if you still want to flush the output buffer.

    0 讨论(0)
提交回复
热议问题