C++ 字符串和数字相互转化的方法总结归纳
一、sscanf和sprintf
sscanf(源字符串,格式,目的变量) 字符串数组转化为数字 理解为string + scanf
sprintf(目的字符串,格式,源变量) 数字转化为字符串数组 理解为string + printf
例如:
#include <cstdio>
int main(){
int n;
char str[10] = "123";
sscanf(str,"%d",&n); //将字符串数组的内容转化为数字
printf("%d",n);
}
输出为
123
#include <cstdio>
int main(){
int n = 1234;
char str[10];
sprintf(str,"%d",n); //将数字内容相应写入字符串
printf("%s",str);
}
输出为
1234
二、atoi、stoi字符串转数字
atoi、stoi均为cstring头文件下的字符处理函数,作用为把字符串转化为数字
atoi(const *char)若参数为string类型,一定先要用c_str()方法进行处理(返回一个指向标准c字符串数组的指针)
stoi(const *string) 函数名为string to integer缩写
其中atoi()不进行范围检查;而stoi()进行范围检查,默认为int,若超出范围则报错
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "2147482", s2 = "-214748";
string s3 = "214748666666663", s4 = "-21474836488";
cout << stoi(s1) << endl;
cout << stoi(s2) << endl;
cout << atoi(s3.c_str()) << endl;
cout << atoi(s4.c_str()) << endl;
return 0;
}
2147482
-214748
301866663
-8
三、数字转字符串
● itoa():将整型值转换为字符串。
● ltoa():将长整型值转换为字符串。
● ultoa():将无符号长整型值转换为字符串。
● gcvt():将浮点型数转换为字符串,取四舍五入。
● ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
● fcvt():指定位数为转换精度,其余同ecvt()。
# include <stdio.h>
# include <stdlib.h>
int main ()
{
int num_int = 435;
double num_double = 435.10f;
char str_int[30];
char str_double[30];
itoa(num_int, str_int, 10); //把整数num_int转成字符串str_int,10表示10进制
gcvt(num_double, 8, str_double); //8代表精度
printf("str_int: %s\n", str_int);
printf("str_double: %s\n", str_double);
return 0;
}