初学C++,总结下在实践中对于几种常见内置类型转换的理解吧。
1、int型与string型的互相转换
最佳实践:
int型转string型
[cpp] view plain copy void int2str(const int &int_temp,string &string_temp) { stringstream stream; stream<<int_temp; string_temp=stream.str(); //此处也可以用 stream>>string_temp }
string型转int型
[html] view plain copy void str2int(int &int_temp,const string &string_temp) { stringstream stream(string_temp); stream>>int_temp; }
在C++中更推荐使用流对象来实现类型转换,以上两个函数在使用时需要包含头文件 #include <sstream>
可选实践:
int型转string型
[html] view plain copy void str2int(int &int_temp,const string &string_temp) { int_temp=atoi(string_temp.c_str()); }
只需要一个函数既可以搞定,atoi()函数主要是为了和C语言兼容而设计的,函数中将string类型转换为c语言的char数组类型作为atoi函数的实参,转化后是int型。
string型转int型
[html] view plain copy void int2str(const int &int_temp,string &string_temp) { char s[12]; //设定12位对于存储32位int值足够 itoa(int_temp,s,10); //itoa函数亦可以实现,但是属于C中函数,在C++中推荐用流的方法 string_temp=s; }
注意,itoa函数在C++中是不被推荐的,在VS中编译会有警告,这里可能跟char数组s的设定有关,如果s设定为小于11在int型数字比较大时会有内存泄漏风险。说明下itoa函数如何使用吧,参数列表中第一个是你要转换的int型变量,第二个是转换后的char型数组变量,第三个是int型的进制,这里认定为10进制表达的int型,如果是16进制就写16。
2、其他类型
float型与string型的转换
建议同样适用流的方法,只要把前面函数中int改为float就可以了。此外还有gcvt函数可以实现浮点数到字符串的转换,atof()函数则实现把字符串转换为浮点数。使用方法如下:
[cpp] view plain copy float num; string str="123.456"; num=atof(str.c_str());[cpp] view plain copy double num=123.456; string str; char ctr[10]; gcvt(num,6,ctr); str=ctr;
其中num默认为double类型,如果用float会产生截断。6指的是保留的有效位数。ctr作为第三个参数默认为char数组来存储转换后的数字。该函数在VS下编译时同样会提示该函数不提倡使用。最后一行将ctr之间转换为str。