字符串数字互转,别再只会用 atoi 了!

大家好,我是 King。欢迎来看今天的文章。
很多朋友写 C++ 代码时,一碰到字符串转数字,顺手就敲个 atoi。这玩意儿老、不好用、还不安全。今天咱就敞开聊聊,现代 C++ 里到底怎么优雅地处理字符串和数字之间的互转。
为啥要告别 atoi?
atoi 是 C 语言时代的老函数了。它最大的毛病是:你传个 "abc" 进去,它悄悄返回 0,根本不告诉你转换失败了。这叫什么事?程序里藏着这种隐患,线上出问题了都找不到原因。
而且 atoi 对 "123abc" 这种串,会返回 123,你以为是成功转换了,实际上后面还有 "abc" 没处理。这种沉默的错误,最容易坑人。
现代 C++ 的正确打开方式 www.haomir.com.cn https://www.644game.com.cn/fgcq/349.html  https://www.887game.com.cn/xkcq/351.html 
1. 字符串 → 数字:用 std::sto 系列函数
C++11 开始,标准库提供了 std::stoi、std::stol、std::stod 等函数,用起来简单又安全。

#include <string>
#include <iostream>

std::string str = "123";
int num = std::stoi(str);  // num = 123

关键好处是:如果转换失败,它会抛异常。这样你就能明明白白捕获错误,而不是被默默吞掉。

std::string bad = "xyz";
try {
    int val = std::stoi(bad);
} catch (const std::invalid_argument& e) {
    // 处理转换失败的情况
}

它还支持处理带单位或后缀的字符串,比如 "123abc" 转成 123,但你可以通过第二个参数知道哪里停下来了:

std::string s = "123abc";
size_t pos;
int num = std::stoi(s, &pos);  // num=123, pos=3

2. 数字 → 字符串:用 std::to_string  https://www.08game.com.cn/mrxf/356.html  https://www.34game.com.cn/gblbb/365.html  https://www.48game.com.cn/yxjl/353.html 
反过来转更简单,一句话:

int num = 456;
std::string str = std::to_string(num);  // str = "456"

浮点数也一样:

double pi = 3.14159;
std::string pi_str = std::to_string(pi);

没有任何复杂操作,干净利落。 https://www.7sfwang.cn/hjcq/307.html  https://www.35game.com.cn/kflb/313.html  https://www.38game.com.cn/rxcq/311.html 
3. 更精细的控制:用 std::ostringstream
如果你需要控制格式(比如保留几位小数、对齐方式),std::ostringstream 是你的好帮手:

#include <sstream>
#include <iomanip>

double val = 12.34567;
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << val;
std::string str = oss.str();  // str = "12.35"

数字转字符串时加前缀、后缀、拼接多个内容,用 ostringstream 非常顺手。
4. C++17 的 std::from_chars 和 std::to_chars
追求极致性能的朋友,可以关注 C++17 带来的这两个函数。它们不分配内存、不抛异常、速度很快:

#include <charconv>
#include <string_view>

std::string_view sv = "12345";
int value;
auto result = std::from_chars(sv.data(), sv.data() + sv.size(), value);
if (result.ec == std::errc()) {
    // 转换成功
}

反过来也一样: https://www.21qj.com/xinkaiwow/1116.html  https://www.330hf.com/zhongbian/1994.html   https://www.338wow.com/xinde/2716.html 

char buffer[20];
int n = 67890;
auto [ptr, ec] = std::to_chars(buffer, buffer + sizeof(buffer), n);
if (ec == std::errc()) {
    std::string result(buffer, ptr);  // 成功得到字符串
}

性能敏感的场景(比如游戏服务器、高频交易、日志处理),这个方案是很好的选择。
各场景怎么选? https://www.110sy.com/xfdt/956.html  https://www.9000jhsf.cn/gaobao/199.html   https://www.7sf.pro/zhaohf/900.html   https://www.tao7sf.cn/cqbb/923.html 
日常开发:std::stoi + std::to_string 足够好,代码清晰。
需要格式控制:std::ostringstream 最灵活。
性能第一,且能接受 C++17:std::from_chars / std::to_chars。
还在用 C++11 以下的老项目:考虑 sscanf / snprintf,但别忘了检查返回值。
一个完整示例

#include <iostream>
#include <string>
#include <sstream>

int main() {
    // 字符串转数字
    std::string input = "  42  ";
    try {
        int num = std::stoi(input);
        std::cout << "转换结果:" << num << std::endl;
    } catch (...) {
        std::cout << "转换失败了" << std::endl;
    }

    // 数字转字符串(带格式)
    double price = 19.9;
    std::ostringstream oss;
    oss << "单价:" << std::fixed << std::setprecision(1) << price << "元";
    std::string msg = oss.str();
    std::cout << msg << std::endl;

    return 0;
}

总结
放下 atoi,拥抱现代 C++ 的标准库工具。写出来的代码更健壮、更安全、更清晰。我把这个标题分享给身边同事时,大家都觉得早该写这样一篇文章了。
希望今天的内容对你有实际帮助。下篇再见 —— King。

posted @ 2026-05-21 19:40  九世師  阅读(11)  评论(0)    收藏  举报