字符串转数字:
方法一: 用ASCII码
char s[1] = {'9'};
int a = s[0] - '0';
cout << "a: " << a << endl;
不过只能进行单个字符转换
方法二:
头文件: <cstdlib>
函数:
int atoi(const char *str): //字符串转int
long atol(const cahr *str): //字符串转long
long long atoll(const cahr *str): //字符串转long long
double atof(const char *str): //字符串转double
转换成哪一个,就调用哪个函数
std::cout << std::atoi("123") + 3 << std::endl; //字符串转数字+3并输出
std::cout << std::atof("123.5") + 3.2 << std::endl; //调用longlong的函数
std::cout << std::atoi("123a5") << std::endl; //遇到字母,只转换前面的数字
或者直接赋值即可
int num = atoi("123");
cout << num;
数字 -> 字符串
//sprintf(char数组, "%d", 变量名);
//定义三个不同类型的数字变量
int a = 10;
long long b = 456;
double c = 13.2;
cout << "数字转字符串" << endl;
//直接打印到屏幕上
std::printf("%d\n", a);
std::printf("%lld", b);
std::printf("%f\n", c);
//放到char数组里
char arr[400] = {};
std::sprintf(arr, "%d", d);
std::cout << arr << std::endl; //输出
std::sprintf(arr, "%lld", k);
std::cout << arr << std::endl;
std::sprintf(arr, "%f", e);
std::cout << arr << std::endl;