C++ 数字 ↔ 字符串 互转(最全实用写法)
·
一、字符串 → 数字
1. 标准库函数(推荐,C++11+)
cpp
运行
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "123";
string s2 = "3.1415";
// 转 int
int a = stoi(s1);
// 转 long
long b = stol(s1);
// 转 double
double c = stod(s2);
// 转 float
float d = stof(s2);
cout << a << " " << b << " " << c << endl;
return 0;
}
2. C 语言老式 atoi / atof
cpp
运行
string s = "456";
int a = atoi(s.c_str());
double b = atof(s.c_str());
二、数字 → 字符串
1. to_string() 最简单(推荐)
支持 int /long/long long /float/double
cpp
运行
#include <iostream>
#include <string>
using namespace std;
int main() {
int n = 666;
double d = 2.333;
string s1 = to_string(n);
string s2 = to_string(d);
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
2. 高精度 / 格式化转换(保留小数、补零)
用 stringstream
cpp
运行
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
double num = 3.1415926;
stringstream ss;
// 保留2位小数
ss << fixed << setprecision(2) << num;
string s = ss.str();
cout << s << endl; // 3.14
return 0;
}
3. stringstream 字符串转数字
cpp
运行
string s = "888";
int x;
stringstream ss(s);
ss >> x;
cout << x;
三、极简总结(背这几句够用)
- 数字转字符串:直接
to_string(数字) - 字符串转整数:
stoi(s) - 字符串转小数:
stod(s) - 要格式化、控制小数位数:用
stringstream + setprecision
更多推荐
所有评论(0)