文章目录
C++类型转换
string 转 int、uint
string str="-3.14";
int32_t b = stoi(str);
uint16_t d = stoi(str);
cout<<"int b:"<<b<<endl;
cout<<"int d:"<<d<<endl;
输出:
string 转 float
string str="-3.14";
float_t a=stof(str);
cout<<"float a:"<<a<<endl;
输出:
string 转 short、ushort
string str1 = "-3";
short e = static_cast< signed short >( std::strtoul(str1.c_str(), NULL, 0) );
ushort f = static_cast< unsigned short >( std::strtoul(str1.c_str(), NULL, 0) );
cout<<"short e:"<<e<<endl;
cout<<"short f:"<<f<<endl;
string 转double
string str1 = "-3";
double_t g = stod(str1);
out<<"double g:"<<g<<endl;
输出:
float转string
//float:方法一:后面会有0
float_t fl = 3.14;
string h = to_string(fl);
cout<<"string h:"<<h<<endl;
//float:方法2
ostringstream str_stream;
str_stream << fl;
string i = str_stream.str();
cout<<"string i:"<<i<<endl;
输出:
int转string
//int
int32_t intj = -3;
uint32_t intk = 3;
string j = to_string(intj);
string k = to_string(intk);
cout<<"string j:"<<j<<endl;
cout<<"string k:"<<k<<endl;
输出:
short转string
//short:方法一
ushort shortl = 3;
string l = to_string(shortl);
cout<<"string l:"<<l<<endl;
//short:方法二
ostringstream str_stream_m;
str_stream_m << shortl;
string m = str_stream_m.str();
cout<<"string m:"<<m<<endl;
输出:
int十进制转十六进制
//int10->16
char strn[4];
int intn = 17;
itoa(intn,strn,16);
cout<<"10->16:"<<strn<<endl;
输出:
int转short
//int->short
uint32_t p = 65533;
short p1 = p;
ushort p2 = p;
cout<<"-int p1:"<<p1<<endl;
cout<<"int p2:"<<p2<<endl;
输出: