#include iostream #include sstream using namespace std; int main(){ /* ---------------------------------- 十六进制,八进制转十进制---------------------------------- */ int decimal1,decimal2; string oct_test = " 75 " ; string hex
#include <iostream> #include <sstream> using namespace std; int main() { /*---------------------------------- 十六进制,八进制转十进制 ----------------------------------*/ int decimal1,decimal2; string oct_test = "75"; string hex_test = "A3"; stringstream ss1; ss1.str(oct_test); ss1>>oct>>decimal1; cout<<"Convert oct to decimal:"<<decimal1<<endl; //ss1.clear();//若不想从新定义stringstream流,必须先清空ss1中的缓存 stringstream ss2; ss2.str(hex_test); ss2>>hex>>decimal2; cout<<"Convert hex to decimal:"<<decimal2<<endl; /*---------------------------------- 十进制转八进制、十六进制 ----------------------------------*/ int decimal; stringstream ss,sss; cout<<"Enter a decimal number:"; cin>>decimal; /*下面两句等价于: cout<<"Convert to hex:"<<hex<<decimal<<endl; */ //十进制转十六进制 ss<<hex<<decimal; cout<<"Convert to hex:"<<ss.str()<<endl; //十进制转八进制 ss.str(""); //同上,若不想从新定义stringstream流,必须先将ss.str()置为空 ss<<oct<<decimal; cout<<"Convert to oct:"<<ss.str()<<endl; system("pause"); return 0; }
运行结果如下:
十六进制结果控制:
将: ss<<hex<<decimal; 替换为: ss << "0x" << uppercase << setfill(‘0‘) << setw(4) << std::hex << decimal;
uppercase : 将小写转大写; setfill(‘0‘): 填充0; setw(4): 设置位宽为4
这里要加入头文件 #include <iomanip>
再次运行结果为: