• C++标准模板(STL)- 输入/输出操纵符-(std::endl)


    操纵符是令代码能以 operator<< 或 operator>> 控制输入/输出流的帮助函数。

    不以参数调用的操纵符(例如 std::cout << std::boolalpha; 或 std::cin >> std::hex; )实现为接受到流的引用为其唯一参数的函数。 basic_ostream::operator<< 和 basic_istream::operator>> 的特别重载版本接受指向这些函数的指针。这些函数(或函数模板的实例化)是标准库中仅有的可取址函数。 (C++20 起)

    以参数调用的操纵符(例如 std::cout << std::setw(10); )实现为返回未指定类型对象的函数。这些操纵符定义其自身的进行请求操作的 operator<< 或 operator>> 。
     

    输出 '\n' 并冲洗输出流

    std::endl

    template< class CharT, class Traits >
    std::basic_ostream& endl( std::basic_ostream& os );

    插入换行符到输出序列 os 并冲入它,如同调用 os.put(os.widen('\n')) 后随 os.flush() 。

    这是仅输出的 I/O 操纵符,可对任何 std::basic_ostream 类型的 out 以表达式 out << std::endl 调用它。

    注意

    可用此操纵符立即产生新行的输出,例如在从长时间运行的进程显示输出、记录多个线程的活动或记录可能不期待地崩溃的程序活动时。在调用 std::system 前亦需要 std::cout 的显式冲入,若产生的进程进行任何屏幕 I/O 。多数其他通常的交互 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 (到操纵后流的引用)

    调用示例

    1. #include <iostream>
    2. #include <chrono>
    3. template<typename Diff>
    4. void log_progress(Diff d)
    5. {
    6. std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d).count()
    7. << " ms passed" << std::endl;
    8. }
    9. int main()
    10. {
    11. std::cout.sync_with_stdio(false); // 一些平台上 stdout 在写 \n 时冲入
    12. volatile int sink = 0;
    13. auto t1 = std::chrono::high_resolution_clock::now();
    14. for (int j = 0; j < 5; ++j)
    15. {
    16. for (int n = 0; n < 10000; ++n)
    17. for (int m = 0; m < 20000; ++m)
    18. {
    19. sink += m * n; // 做一些工作
    20. }
    21. auto now = std::chrono::high_resolution_clock::now();
    22. log_progress(now - t1);
    23. }
    24. return 0;
    25. }

    输出

  • 相关阅读:
    Abnova丨Abnova 哺乳动物蛋白质表达方案
    HTML5离线储存
    【无人机路径规划】基于改进差分算法实现三维多无人机协同航迹规划附matlab代码
    107.网络安全渗透测试—[权限提升篇5]—[Linux Cron Jobs 提权]
    ChatGPT 火爆全球,我们能抓住的下一个风口在哪?
    ES6新特性:变量的解构赋值
    Fiddler抓包原理及其配置
    面试必学:输入 URL到页面的全过程-----五步完成、简单明了
    国家开放大学 试题练习
    C++ stack,queue,priority_queue容器适配器模拟实现
  • 原文地址:https://blog.csdn.net/qq_40788199/article/details/133234096