一、 int与string
使用C++的流(需要#include<sstream>
)
1.int=>string
void int2str(const int &int_temp,string &string_temp)
{
stringstream stream;
stream<<int_temp;
string_temp=stream.str(); //此处也可以用 stream>>string_temp
}
2.string=>int
void str2int(int &int_temp,const string &string_temp)
{
stringstream stream(string_temp);
stream>>int_temp;
}
C语言(需要#include <stdlib.h>
)
1.int=>string
void int2str(const int &int_temp,string &string_temp)
{
char s[12]; //设定12位对于存储32位int值足够
itoa(int_temp,s,10);
string_temp=s;
}
itoa函数参数列表中第一个是你要转换的int型变量,第二个是转换后的char型数组变量,第三个是int型的进制,这里认定为10进制表达的int型,如果是16进制就写16。
2019.1.26更新:cplusplus.com关于itoa函数的说明如下:
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
意思是这不是c++标准函数,仅仅是某些编译器支持。
最好使用sprintf进行int=>string的转化
用法:
sprintf(*p, "%d", num); //将num转为字符串输入到 p 中
string int2str(const int &int_temp)
{
string string_temp;
char s[12];
sprintf(s,"%d",int_temp);
string_temp=s;
return string_temp;
}
2.string=>int
void str2int(int &int_temp,const string &string_temp)
{
int_temp=atoi(string_temp.c_str());
}
atoi()函数主要是为了和C语言兼容而设计的,函数中将string类型转换为C语言的char数组类型作为atoi函数的实参,转化后是int型。
二、float/double与string
流的方法也适用,只需把int改为float
使用atof和gcvt的方法如下:
string=>float
float num;
string str="123.456";
num=atof(str.c_str());
double=>string
double num=123.456;
string str;
char ctr[10];
gcvt(num,6,ctr);
str=ctr;
其中num默认为double类型,如果用float会产生截断。6指的是保留的有效位数。ctr作为第三个参数默认为char数组来存储转换后的数字。