使用控制符(manipulator),修改显示时的计数系统:
控制符位于名称空间 std 中,实际上是函数,但不是成员函数,不必通过对象来调用。
进制 | 控制符 |
八进制(octal) | oct |
十进制(decimal) | dec |
十六进制(hexadecimal) | hex |
使用方式:
hex(cout) 或 cout<<hex;完成上述设置后,直到将格式状态设置为其他选项为止。
#include<iostream>
#include<bitset> // 输出为二进制
int main()
{
using namespace std;
cout << "Enter an integer: ";
int n;
cin >> n;
cout << "n n*n\n";
cout << n << " " << n * n << " (decimal)\n";
cout << hex;
cout << n << " ";
cout << n * n << " (hexadecimal)\n";
cout << oct << n << " " << n * n << " (octal)\n";
dec(cout);
cout << n << " " << n * n << " (decimal)\n";
cout << (n << 2) << endl;
cout << bitset<8>(n) << endl; // < > 中的数字指定输出的位数
return 0;
}