std::dec, std::hex, std::oct
来自 cppreference.com
定义在头文件 <ios> 中 |
||
std::ios_base& dec( std::ios_base& str ); |
(1) | |
std::ios_base& hex( std::ios_base& str ); |
(2) | |
std::ios_base& oct( std::ios_base& str ); |
(3) | |
修改整数 I/O 的默认数字进制。
这是一个 I/O 操作符。它可以与表达式一起使用,例如 out << std::hex,其中 out
为 std::basic_ostream 类型,或者与表达式一起使用,例如 in >> std::hex,其中 in
为 std::basic_istream 类型。
内容 |
[编辑] 参数
str | - | 对 I/O 流的引用 |
[编辑] 返回值
str(操作后的流的引用)。
[编辑] 示例
运行此代码
#include <bitset> #include <iostream> #include <sstream> int main() { std::cout << "The number 42 in octal: " << std::oct << 42 << '\n' << "The number 42 in decimal: " << std::dec << 42 << '\n' << "The number 42 in hex: " << std::hex << 42 << '\n'; int n; std::istringstream("2A") >> std::hex >> n; std::cout << std::dec << "Parsing \"2A\" as hex gives " << n << '\n'; // the output base is sticky until changed std::cout << std::hex << "42 as hex gives " << 42 << " and 21 as hex gives " << 21 << '\n'; // Note: there is no I/O manipulator that sets up a stream to print out // numbers in binary format (e.g. bin). If binary output is necessary // the std::bitset trick can be used: std::cout << "The number 42 in binary: " << std::bitset<8>{42} << '\n'; }
输出
The number 42 in octal: 52 The number 42 in decimal: 42 The number 42 in hex: 2a Parsing "2A" as hex gives 42 42 as hex gives 2a and 21 as hex gives 15 The number 42 in binary: 00101010
[编辑] 参见
更改用于整数 I/O 的进制 (函数) | |
控制是否使用前缀来指示数字进制 (函数) |