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>> 。

定义于头文件 <iomanip>

更改用于整数 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<CharT, Traits> 或 std::basic_istream<CharT, Traits> 类型的流名称,则表达式 str << setbase(base) 或 str >> setbase(base) 表现为如同执行下列代码:

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

调用示例

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
    std::cout << "Parsing string \"10 0x10 010\"\n";

    int n1, n2, n3;
    std::istringstream s("10 0x10 010");
    s >> std::setbase(16) >> n1 >> n2 >> n3;
    std::cout << "hexadecimal parse: " << n1 << ' '
              << n2 << ' ' << n3 << std::endl;

    s.clear();
    s.seekg(0);
    s >> std::setbase(0) >> n1 >> n2 >> n3;
    std::cout << "prefix-dependent parse: " << n1 << ' '
              << n2 << ' ' << n3 << std::endl;

    std::cout << "hex output: " << std::setbase(16)
              << std::showbase << n1 << ' ' << n2
              << ' ' << n3 << std::endl;

    return 0;
}

输出

更改填充字符

std::setfill

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

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

参数

c - 填充字符的新值

返回值

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

out.fill(n);

注意

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

 调用示例

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "default fill: " << std::setw(10) << 42 << std::endl
              << "setfill('*'): " << std::setfill('*')
              << std::setw(10) << 42 << std::endl;

    return 0;
}

输出

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/133235242