使用std::endl可能有点低效,因为它实际上执行两个任务:它将光标移到下一行,并“刷新”输出(确保它立即显示在屏幕上)。 当使用std::cout向控制台写入文本时,std::cout通常会刷新输出(如果不刷新,通常也没有关系),所以有std::endl刷新并不重要。
因此,通常首选使用’ \n '字符。 ’ \n ‘字符将光标移到下一行,但不执行冗余刷新,因此性能更好。 字符’ \n '也更容易阅读,因为它更短,可以嵌入到现有的文本中。
#include <iostream> // for std::cout
int main() {
int x{ 5 };
std::cout << "x is equal to: " << x << '\n'; // Using '\n' standalone
std::cout << "And that's all, folks!\n"; // Using '\n' embedded into a double-quoted piece of text (note: no single quotes when used this way)
return 0;
}
x is equal to: 5
And that's all, folks!
本文讨论了在C++编程中使用std::endl与'
'的区别。std::endl不仅换行,还会刷新输出,可能导致性能下降。建议使用'
'来替换std::endl,以减少不必要的刷新操作,提升程序运行效率。示例代码展示了如何在实际输出中应用'
'。
44

被折叠的 条评论
为什么被折叠?



