平时有可能会用到将int的1转换为string的"1"的题型,下面对C/C++字符串和数字的相互转换进行整理:
int、long 和 double 等类型,有时也需要转换为字符串形式,这样结果字符串才能立即输出到文件或其他输入输出设备,或者存入内存中的某个字符串对象,供以后使用。
to_string()函数是C++ 11 提供了若干 to_string(T value) 函数来将 T 类型的数字值转换为字符串形式。
string to_string(int lcc)
string to_string(long lcc)
string to_string(double lcc)
这个函数在一些编译环境下面是不能直接使用的会报错:
[Error] 'to_string' was not declared in this scope
因为to_string这个函数只有C++11才有,这个报错应该是在旧版本C++使用该函数的原因,如果不能使用需要自己写一个函数:
在流文件下,需要使用“sstream”头文件:
template
std::string to_string(T value)
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
程序代码:
#include
#include
#include
using namespace std;
template
std::string to_string(T value)
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
int main(){
int lcc1 = 1;
long lcc2 = 122;
double lcc3 = 2.1;
string s1 = to_string(lcc1);
string s2 = to_string(lcc2);
string s3 = to_string(lcc3);
cout<
运行结果:
atoi和atof:
程序代码:
#include
#include
using namespace std;
int main(){
int n;
double db;
n = atoi("1");
db = atof("1.1");
printf("%d\n",n);
printf("%f\n",db);
return 0;
}
运行结果:
还可以使用字符串流,因为字符串流比较难理解,就不在此叙述,有兴趣的读者可以查看:http://c.biancheng.net/view/1527.html
程序代码:
#include
int main(){
int n;
long long l;
double db;
char str1[100] = "1";
char str2[100] = "1234567";
char str3[100] = "123.213";
sscanf(str1,"%d",&n);
sscanf(str2,"%lld",&l);
sscanf(str3,"%lf",&db);
printf("%d\n",n);
printf("%lld\n",l);
printf("%f\n",db);
return 0;
}
运行结果:
程序代码:
#include
int main(){
int n=12;
long long l=3222;
double db=3.1415;
char str[100];
sprintf(str,"%d %lld %f",n,l,db);
printf("str=%s\n",str);
return 0;
}
运行结果:
atoi和atof:
程序代码:
#include
#include
using namespace std;
int main(){
int n;
double db;
char a[]="23";
char b[]="1.1";
n = atoi(a);
db = atof(b);
printf("%d\n",n);
printf("%f\n",db);
return 0;
}
运行结果:
itoa和gcvt:
程序代码:
#include
#include
using namespace std;
int main(){
char s1[10];
char s2[10];
itoa(1, s1, 10);
gcvt(1.1, 10, s2);
printf("%s\n",s1);
printf("%s\n",s2);
return 0;
}
运行结果:
此外还有
整数:
小数:
gcvt必须提供接收结果的缓冲区buf,而ecvt、fcvt由头文件提供缓冲区,直接读返回值字符串即可;
此外itoa()还可以用于进制转换,详情请参考: