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


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

    定义于头文件

    更改用于整数 I/O 的基数

    std::setbase

    /*unspecified*/ setbase( int base );

    设置流的数值底。用于表达式 out << setbase(base) 或 in >> setbase(base) 时,取决于 base 的值,更改流 outinbasefield 标志:

    • 值 16 设置 basefield 为 std::ios_base::hex
    • 值 8 设置 std::ios_base::oct
    • 值 10 设置 std::ios_base::dec 。

    异于 8 、 10 或 16 的 base 值重置 basefield 为零,这对应十进制输出和依赖前缀的输入。

    参数

    base-basefield 的新值

    返回值

    返回未指定类型的对象,使得若 str 为 std::basic_ostream 或 std::basic_istream 类型的流名称,则表达式 str << setbase(base) 或 str >> setbase(base) 表现为如同执行下列代码:

    1. str.setf(base == 8 ? std::ios_base::oct :
    2. base == 10 ? std::ios_base::dec :
    3. base == 16 ? std::ios_base::hex :
    4. std::ios_base::fmtflags(0),
    5. std::ios_base::basefield);

    调用示例

    1. #include <iostream>
    2. #include <sstream>
    3. #include <iomanip>
    4. int main()
    5. {
    6. std::cout << "Parsing string \"10 0x10 010\"\n";
    7. int n1, n2, n3;
    8. std::istringstream s("10 0x10 010");
    9. s >> std::setbase(16) >> n1 >> n2 >> n3;
    10. std::cout << "hexadecimal parse: " << n1 << ' '
    11. << n2 << ' ' << n3 << std::endl;
    12. s.clear();
    13. s.seekg(0);
    14. s >> std::setbase(0) >> n1 >> n2 >> n3;
    15. std::cout << "prefix-dependent parse: " << n1 << ' '
    16. << n2 << ' ' << n3 << std::endl;
    17. std::cout << "hex output: " << std::setbase(16)
    18. << std::showbase << n1 << ' ' << n2
    19. << ' ' << n3 << std::endl;
    20. return 0;
    21. }

    输出

    更改填充字符

    std::setfill

    template< class CharT >
    /*unspecified*/ setfill( CharT c );

    用于表达式 out << setfill(c) 时,它设置流 out 的填充字符为 c

    参数

    c-填充字符的新值

    返回值

    返回未指定类型对象,使得若 out 为 std::basic_ostream 类型输出流的名称,则表达式 out << setfill(n) 表现如同执行下列代码:

    out.fill(n);

    注意

    可用 std::ostream::fill 获得当前填充字符。

     调用示例

    1. #include <iostream>
    2. #include <iomanip>
    3. int main()
    4. {
    5. std::cout << "default fill: " << std::setw(10) << 42 << std::endl
    6. << "setfill('*'): " << std::setfill('*')
    7. << std::setw(10) << 42 << std::endl;
    8. return 0;
    9. }

    输出

  • 相关阅读:
    N皇后问题(分支限界法)
    angular:简单实现图片如果超过屏幕高度则滚动置顶;没超过则水平垂直居中
    JSP简介
    情绪价值的一点点整理
    计算机复试面试题总结
    BUUCTF-PWN-第一页writep(32题)
    HCIA-R&S自用笔记(24)ACL
    C++ std::tr1::function和std::tr1::bind模板类介绍,qt测试
    SpringBoot-运维实用篇复习(全)
    结对编程大法好
  • 原文地址:https://blog.csdn.net/qq_40788199/article/details/133235242