What's the difference between std::endl and '\n'

蓝咒 提交于 2021-02-09 11:10:46

问题


I've read the difference between std::endl and '\n' is that std::endl flushes the buffer and '\n' doesn't. However, as far as I know stdout on linux is line-buffered anyway, so does it mean that std::cout << ... << std::endl is the same as std::cout << ... << '\n'?


回答1:


std::ostream os;

os << std::endl; // more concise

os << '\n' << std::flush; // more explicit about flushing

Those two lines have the exact same effect.

The manual flushing is often a waste of time:

  • If the output stream is line-buffered, which should be the case for std::cout if it connects to an interactive terminal and the implementation can detect that, then printing \n already flushes.

  • If the output stream is paired with an input stream you read from directly afterwards (std::cout and std::cin are paired), then reading already flushes.

  • If you nobody waits for the data to arrive at its destination, flushing is again just going to waste.




回答2:


This std::cout << ... << std::endl and this std::cout << ... << '\n' are not exactly the same. In the last one, the newline \n is streamed to the output. In most cases this will be interpreted by a console as a newline. But std::endl means (as you already mentioned) exactly flush and newline in the output console.

Assume you would write this in a document. In Linux the \n is sufficient. But Windows expects \r\n. So the new lines will not occur using \n and e.g. Notepad++ in Windows.



来源:https://stackoverflow.com/questions/64253865/whats-the-difference-between-stdendl-and-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!