std::endl
Defined in header <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操作程序,可以用如下表达式调用它out << std::endl对任何out类型std::basic_ostream...
注记
该机械手可用于立即产生一行输出,例如,当显示来自长期运行的进程的输出、多线程的日志活动或可能意外崩溃的程序日志活动时。一次明显的冲过...std::cout在调用std::system,如果生成的进程执行任何屏幕I/O。在大多数其他通常的交互I/O场景中,std::endl在使用时是多余的。std::cout因为来自std::cin,输出到std::cerr,或者程序终止会强制调用std::cout.flush()...的使用std::endl代替'\n'在某些来源的鼓励下,可能会显著降低产出绩效。
在许多实现中,标准输出是行缓冲和写入的。'\n'导致同花顺,除非std::ios::sync_with_stdio(false)被处决了。在这种情况下,没有必要endl只会降低文件输出的性能,而不是标准输出。
这个wiki上的代码示例沿着Bjarne Stroustrup和C++核心指南只在必要时冲洗标准输出。
当需要刷新不完整的输出行时,std::flush可以使用机械手。
当输出的每个字符都需要刷新时,std::unitbuf可以使用机械手。
参数
os | - | reference to output stream |
|---|
返回值
os%28操作后对流的引用%29。
例
使用\n代替Endl,输出将是相同的,但可能不会实时出现。
二次
#include <iostream>
#include <chrono>
template<typename Diff>
void log_progress(Diff d)
{
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d).count()
<< " ms passed" << std::endl;
}
int main()
{
std::cout.sync_with_stdio(false); // on some platforms, stdout flushes on \n
volatile int sink = 0;
auto t1 = std::chrono::high_resolution_clock::now();
for (int j=0; j<5; ++j)
{
for (int n=0; n<10000; ++n)
for (int m=0; m<20000; ++m)
sink += m*n; // do some work
auto now = std::chrono::high_resolution_clock::now();
log_progress(now - t1);
}
}二次
产出:
二次
487 ms passed
974 ms passed
1470 ms passed
1965 ms passed
2455 ms passed二次
另见
unitbufnounitbuf | controls whether output is flushed after each operation (function) |
|---|---|
flush | flushes the output stream (function template) |
flush | synchronizes with the underlying storage device (public member function of std::basic_ostream) |
© cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

