C++ 数字与字符串互转

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;
}
补充说明
  1. 支持正负号stoi("-456")-456
  2. 自动截断:遇到非数字字符停止解析,stoi("789abc")789
  3. 越界/非法字符串会抛出异常,生产环境建议加异常捕获。

2. C 风格函数(<cstdlib>

兼容所有 C++ 版本,无异常,靠返回值判断。

头文件:#include <cstdlib>

  • atoi(char*):字符串转 int
  • atol(char*):转 long
  • atoll(char*):转 long long
  • atof(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 指定最大长度,防止越界。


三、常用场景总结 & 选型建议

  1. 简单互转(C++11+)

    • 数字→字符串:优先 to_string()
    • 字符串→数字:优先 stoi/stod/stoll
  2. 需要格式化(控制小数、对齐、进制)

    统一用 stringstream + <iomanip>

  3. 兼容古老编译器

    使用 C 风格 atoi / atof / sprintf


四、常见坑点

  1. to_string 浮点会补多余 0,要用精度控制请换 stringstream
  2. stoi 传入空串、全字母、数值溢出会抛异常。
  3. atoi 遇到非法内容一律返回 0,不会告警。
  4. string 传给 C 函数必须加 .c_str() 转为 const char*
相关推荐
陈猪的杰咪1 小时前
DeepSeek V4 中转方案全解析 | Flash 成本仅为 GPT 的 1/90
java·人工智能·gpt·spring
zlpzlpzyd1 小时前
spring boot 4.1发布
java·数据库·spring boot
无籽西瓜a1 小时前
Plan-and-Execute 里的 DAG 是怎么工作的
java·后端·ai·agent·dag
小灰灰搞电子1 小时前
C++ boost::asio 详解:网络编程领域的“瑞士军刀“
网络·c++·boost
ch.ju1 小时前
Java Programming Chapter 4——The difference between overloading and overwriting.
java·开发语言
我命由我123451 小时前
Android 开发问题:View 的 getWidth、getHeight 方法返回的值都为 0
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
满怀冰雪1 小时前
第12篇-二分答案法-当答案不好求时如何反向搜索
java·算法
我登哥MVP1 小时前
SpringCloud 核心组件解析:服务网关
java·spring boot·后端·spring·spring cloud·java-ee·maven
KaMeidebaby1 小时前
卡梅德生物技术快报|兔单克隆抗体应用实战:禽源病原 IFA 检测全流程拆解
前端·人工智能·物联网·算法·百度