分C++ 标准库主流写法(C++11 及以上推荐)、C 风格写法,附常用场景、示例与注意事项。
一、字符串 → 数字
1. C++11 标准函数(推荐,<string>)
头文件:#include <string>
| 函数 | 作用 |
|---|---|
stoi(s) |
字符串转 int |
stol(s) |
字符串转 long |
stoll(s) |
字符串转 long long |
stof(s) |
字符串转 float |
stod(s) |
字符串转 double |
stold(s) |
字符串转 long double |
示例
cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "123";
string s2 = "3.1415";
int a = stoi(s1);
double b = stod(s2);
cout << a << endl; // 123
cout << b << endl; // 3.1415
return 0;
}
补充说明
- 支持正负号 :
stoi("-456")→-456 - 自动截断:遇到非数字字符停止解析,
stoi("789abc")→789 - 越界/非法字符串会抛出异常,生产环境建议加异常捕获。
2. C 风格函数(<cstdlib>)
兼容所有 C++ 版本,无异常,靠返回值判断。
头文件:#include <cstdlib>
atoi(char*):字符串转 intatol(char*):转 longatoll(char*):转 long longatof(char*):转 double
示例
cpp
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string s = "999";
int num = atoi(s.c_str()); // c_str() 转 const char*
cout << num << endl;
return 0;
}
缺点:非法输入/溢出不会报错,直接返回
0,难以排查问题。
二、数字 → 字符串
1. C++11 to_string(最简单,推荐)
头文件:#include <string>
支持所有整型、浮点型,直接转换。
示例
cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n1 = 100;
double n2 = 2.718;
string str1 = to_string(n1);
string str2 = to_string(n2);
cout << str1 << endl; // "100"
cout << str2 << endl; // "2.718000"
return 0;
}
注意:浮点数会默认补后缀 0,无法自定义小数位数。
2. 字符串流 stringstream(灵活,可格式化)
需要控制小数位数、进制、拼接 时首选。
头文件:#include <sstream>
用法1:数字转字符串
cpp
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip> // 控制精度 setprecision
using namespace std;
int main()
{
double pi = 3.1415926;
string res;
stringstream ss;
// 设置保留4位小数
ss << fixed << setprecision(4) << pi;
ss >> res;
cout << res << endl; // 3.1416
return 0;
}
用法2:字符串转数字
cpp
string s = "888";
int num;
stringstream ss(s);
ss >> num;
cout << num;
清空流复用
多次使用要清空缓冲区:
cpp
ss.clear(); // 清除状态标记
ss.str(""); // 清空内容
3. C 风格 sprintf / snprintf
底层 C 函数,适合老代码,需注意缓冲区溢出。
头文件:#include <cstdio>
cpp
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
char buf[20];
int num = 666;
sprintf(buf, "%d", num); // 数字转 char*
string str(buf);
cout << str << endl;
return 0;
}
安全写法:用
snprintf指定最大长度,防止越界。
三、常用场景总结 & 选型建议
-
简单互转(C++11+)
- 数字→字符串:优先
to_string() - 字符串→数字:优先
stoi/stod/stoll
- 数字→字符串:优先
-
需要格式化(控制小数、对齐、进制)
统一用
stringstream + <iomanip> -
兼容古老编译器
使用 C 风格
atoi / atof / sprintf
四、常见坑点
to_string浮点会补多余 0,要用精度控制请换stringstream。stoi传入空串、全字母、数值溢出会抛异常。atoi遇到非法内容一律返回 0,不会告警。string传给 C 函数必须加.c_str()转为const char*。