C++ `endl` 与 ` ` 的区别
C++ endl
与 \n
的区别
std::cout << std::endl
: 插入换行并刷新缓存区 (flush the buffer)std::cout << "\n"
: 插入换行
其中关于 std::endl
,C++ Primer 中是这样介绍的:
“
endl
, which is a special value called a manipulator. Writingendl
has the effect of ending the current line and flushing the buffer associated with that device. Flushing the buffer ensures that all the output the program has generated so far is actually written to the output stream, rather than sitting in memory waiting to be written.”-- Stanley B. Lippman. “C++ Primer, Fifth Edition (Jason Arnold's Library).”
刷新操作能够保证程序中推送到 cout
的数据全部输出,而不是继续留存在缓存区以 buffer 形式存在。大多数情况下这是最后一步输出操作所期望的结果。如果还没结束输出,那可直接用 \n
。