c++中常见的类型转换int,string,float

来源:互联网 发布:城市衣柜cevel淘宝店 编辑:程序博客网 时间:2024/04/30 08:53

1、int型与string型的互相转换

最佳实践:

int型转string型

 

[cpp] view plain copy
  1. void int2str(const int &int_temp,string &string_temp)  
  2. {  
  3.         stringstream stream;  
  4.         stream<<int_temp;  
  5.         string_temp=stream.str();   //此处也可以用 stream>>string_temp  
  6. }  

 

string型转int型

 

[html] view plain copy
  1. void str2int(int &int_temp,const string &string_temp)  
  2. {  
  3.     stringstream stream(string_temp);  
  4.     stream>>int_temp;  
  5. }  


在C++中更推荐使用流对象来实现类型转换,以上两个函数在使用时需要包含头文件 #include <sstream>


可选实践:

int型转string型

 

[html] view plain copy
  1. void str2int(int &int_temp,const string &string_temp)  
  2. {  
  3.     int_temp=atoi(string_temp.c_str());                     
  4. }  

只需要一个函数既可以搞定,atoi()函数主要是为了和C语言兼容而设计的,函数中将string类型转换为C语言的char数组类型作为atoi函数的实参,转化后是int型。

 

string型转int型

 

[html] view plain copy
  1. void int2str(const int &int_temp,string &string_temp)  
  2. {  
  3.     char s[12];             //设定12位对于存储32位int值足够  
  4.     itoa(int_temp,s,10);            //itoa函数亦可以实现,但是属于C中函数,在C++中推荐用流的方法  
  5.     string_temp=s;  
  6. }  

注意,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
  1. float num;  
  2. string str="123.456";  
  3. num=atof(str.c_str());  

 

[cpp] view plain copy
  1. double num=123.456;  
  2. string str;  
  3. char ctr[10];  
  4. gcvt(num,6,ctr);  
  5. str=ctr;  
其中num默认为double类型,如果用float会产生截断。6指的是保留的有效位数。ctr作为第三个参数默认为char数组来存储转换后的数字。该函数在VS下编译时同样会提示该函数不提倡使用。最后一行将ctr之间转换为str
0 0
原创粉丝点击