数字与字符串之间的转化
在C中:
方法:
- C标准库中的sprintf,sscanf
- 字符串转数字 sscanf
#include<stdio.h>
//字符串转数字
void Testsscanf()
{
//字符串转化为整数
char str1[] = "1234567";
int a;
sscanf(str1,"%d",&a);
printf("%d\n",a);
//字符串转化为浮点数
char str2[] = "123.456";
double d;
sscanf(str2,"%lf",&d);
printf("%lf\n",d);
//十六进制转化为10进制
char str3[10];
int c=175;
sprintf(str3,"%x",a);
printf("%s\n",str1);
}
2. 数字转字符串 sprintf
//数字转字符串
void Testsprintf()
{
char str1[10];
int a=1234321;
sprintf(str1,"%d",a);
printf("%s\n",str1);
char str2[10];
double b=123.321;
sprintf(str2,"%.3lf",a);
printf("%s\n",str1);
char str3[10];
int c=175;
sprintf(str3,"%x",a);//10进制转换成16进制,如果输出大写的字母是sprintf(str,"%X",a)
printf("%s\n",str1);
}
- C标准库中的atoi、atof、atol、atoll(C++11标准)函数将字符串转化为int、double、long、long long 型
- atoi函数
功能:把字符串转化为整形数
原型: int atoi(const char *nptr);
注:需要用到的头文件: #include <stdlib.h>
2. itoa函数
功能:将整形数转化为字符串
原型:char *itoa(int value, char *string, int radix);
value: 待转化的整数。
radix: 是基数的意思,即先将value转化为radix进制的数,范围介于2-36,比如10表示10进制,16表示16进制。
* string: 保存转换后得到的字符串。
返回值:char * : 指向生成的字符串, 同*string。
注:需要用到的头文件: #include <stdlib.h>
在C++中:
方法:用C++中stringstream;
注:需要引入头文件 #include<sstream>
- 数字转字符串
#include<sstream>
#include<string>
string num2str(double i)
{
stringstream ss;
ss << i;
return ss.str();
}
- 字符串转数字
#include<sstream>
#include<string>
int str2num(string s)
{
int num;
stringstream ss(s);
ss >> num;
return num;
}
更多使用详见:
https://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html