C++标准模板(STL)- 输入/输出操纵符-(std::flush,std::ends)

操纵符是令代码能以 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>> 。
 

输出 '\0'

std::ends

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

如同以调用 os.put(CharT()) 插入空字符到输出序列中 os

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

注意

此操纵符典型地为 std::ostrstream 在关联输出缓冲区需要为空终止,以作为 C 字符串处理时使用。

不同于 std::endl ,此操纵符不冲入流。

参数

os-到输出流的引用

返回值

os (到插入空字符后的流的引用)

调用示例

#include <cstdio>
#include <strstream>

int main()
{
    std::ostrstream oss;
    oss << "Sample text: " << 42 << std::ends;
    std::printf("%s\n", oss.str());
    oss.freeze(false); // 启用内存解分配

    return 0;
}

 输出

冲洗输出流

std::flush

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

如同以调用 os.flush() 冲入输出序列 os

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

注意

此操纵符可用于立即产生输出的不完整行,例如在从长时间运行的进程显示输出、记录多个线程的活动或记录可能不期待地崩溃的程序活动时。若产生的进程进行任何屏幕 I/O 大量,则调用 std::system 前亦需要 std::cout 的显式冲入(常见例子为 Windows 上的 std::system("pause") )。多数其他通常的交互 I/O 场景中,使用 std::cout 时 std::endl 是冗余的,因为任何来自 std::cin 的输入、到 std::cerr 的输出或程序终止强制调用 std::cout.flush() 。

需要冲入完整行时,可使用 std::endl 操纵符。

每次输出操作都需要冲入时,可使用 std::unitbuf 操纵符。

参数

os-到输出流的引用

返回值

os (到操纵后的流的引用)

调用示例

#include <iostream>
#include <chrono>

template<typename Diff>
void log_progress(Diff d)
{
    std::cout << "..("
              << std::chrono::duration_cast<std::chrono::milliseconds>(d).count()
              << " ms).." << std::flush;
    std::cout << std::endl;
}

int main()
{
    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;    // 做一些工作
            }
        auto now = std::chrono::high_resolution_clock::now();
        log_progress(now - t1);
    }
    std::cout << std::endl;

    return 0;
}

输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值