std::endl
来自cppreference.com
在标头 <ostream> 定义
|
||
template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os ); |
||
插入换行符到输出序列 os 并冲洗它,如同调用 os.put(os.widen('\n')) 后随 os.flush()。
这是仅输出的 I/O 操纵符,可对任何 std::basic_ostream 类型的 out
以表达式 out << std::endl 调用它。
注解
可用此操纵符立即产生新行的输出,例如从长时间运行的进程中显示输出,记录多个线程的活动,或记录可能非预期地崩溃的程序活动。若产生的进程进行任何屏幕 I/O,则在调用 std::system 前亦需要 std::cout 的显式冲洗。多数其他常见的交互 I/O 场景中,使用 std::cout 时 std::endl
是冗余的,因为任何来自 std::cin 的输入、到 std::cerr 的输出或程序终止都会强制调用 std::cout.flush()。某些源代码中鼓励用 std::endl
代替 '\n',这可能显著地降低输出性能。
多数实现中,标准输出是行缓冲的,而写入 '\n' 就会导致冲洗,除非执行 std::ios::sync_with_stdio(false)。这些情形中,不必要的 endl
只会降低文件输出而非标准输出的的性能。
此维基上的代码示例遵循 Bjarne Stroustrup 和《C++ 核心方针》,只在需要时冲洗标准输出。
需要冲洗不完整的行时,可使用 std::flush 操纵符。
需要冲洗每个字节的输出时,可使用 std::unitbuf 操纵符。
参数
os | - | 到输出流的引用 |
返回值
os(到操纵后流的引用)。
示例
以 '\n' 替代 endl
,输出会相同,但可能不会实时出现。
运行此代码
#include <chrono> #include <iostream> template<typename Diff> void log_progress(Diff d) { std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d) << " passed" << std::endl; } int main() { std::cout.sync_with_stdio(false); // 一些平台上 stdout 在写 \n 时冲洗 static volatile int sink{}; const auto t1 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 10000; ++j) for (int k = 0; k < 20000; ++k) sink += i * j * k; // 做一些工作 log_progress(std::chrono::high_resolution_clock::now() - t1); } }
可能的输出:
566ms passed 1133ms passed 1699ms passed 2262ms passed 2829ms passed
参阅
控制是否每次操作后冲洗输出 (函数) | |
冲洗输出流 (函数模板) | |
与底层存储设备同步 ( std::basic_ostream<CharT,Traits> 的公开成员函数) |