C++: "std::endl" vs "\n"

Many C++ books contain example code like this...

std::cout << "Test line" << std::endl;

...so I've always done that too. But I've seen a lot of code from working developers like this instead:

std::cout << "Test linen";

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?


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 .


The difference can be illustrated by the following:

std::cout << std::endl;

is equivalent to

std::cout << 'n' << std::flush;

So,

  • Use std::endl If you want to force an immediate flush to the output.
  • Use n if you are worried about performance (which is probably not the case if you are using the << operator).
  • I use n on most lines.
    Then use std::endl at the end of a paragraph (but that is just a habit and not usually necessary).

    Contrary to other claims, the n character is mapped to the correct platform end of line sequence only if the stream is going to a file ( std::cin and std::cout being special but still files (or file-like)).


    可能存在性能问题, std::endl强制刷新输出流。

    链接地址: http://www.djcxy.com/p/30754.html

    上一篇: 将整个ASCII文件读入C ++ std :: string

    下一篇: C ++:“std :: endl”vs“\ n”