C++ “endl”和“\n”之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4512631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:37:07  来源:igfitidea点击:

Difference between "endl" and "\n"

c++newlineiostreamcoutendl

提问by Nawaz

Possible Duplicate:
C++: “std::endl” vs “\n”

可能的重复:
C++:“std::endl”与“\n”

I'm wondering if there is any significantdifference between these two ways to print newline :

我想知道这两种打印换行符的方式是否有任何显着差异:

cout << endl;  //approach1
cout << "\n";  //approach2

Is there any practical difference?

有什么实际区别吗?

回答by peoro

Yes, they're different.

是的,它们是不同的。

"\n"is just a string of length 1 that gets appended to stdout.

"\n"只是附加到标准输出的长度为 1 的字符串。

std::endl, instead, is an object that will cause to append the newline character ("\n") AND to flush stdout buffer. For this reason it will take more processing.

std::endl,相反,是一个对象,它将导致附加换行符 ( "\n") 并刷新标准输出缓冲区。出于这个原因,它将需要更多的处理。