文章

C++ 字符串转数字 stoi/stod

C++ 字符串转数字 stoi/stod

C++ 字符串转数字 stoi/stod

C++11 提供了一系列字符串转数字的函数,声明在 <string> 中。

一、常用函数

函数说明
stoi(str)字符串转 int
stol(str)字符串转 long
stoll(str)字符串转 long long
stoul(str)字符串转 unsigned long
stoull(str)字符串转 unsigned long long
stof(str)字符串转 float
stod(str)字符串转 double
stold(str)字符串转 long double

二、基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1 = "12345";
    string s2 = "3.14159";
    string s3 = "-42";

    int i = stoi(s1);           // 12345
    double d = stod(s2);        // 3.14159
    long long ll = stoll(s3);   // -42

    cout << i << endl;   // 输出: 12345
    cout << d << endl;   // 输出: 3.14159
    cout << ll << endl;  // 输出: -42

    return 0;
}

三、自动跳过前导空白

1
2
string s = "   123abc";
int n = stoi(s);  // n = 123,自动跳过空格

四、指定进制(stoi 特有)

1
2
3
4
5
6
7
8
string bin = "1010";
string hex = "ff";

int a = stoi(bin, nullptr, 2);   // 二进制转十进制,输出: 10
int b = stoi(hex, nullptr, 16);  // 十六进制转十进制,输出: 255

cout << a << endl;  // 10
cout << b << endl;  // 255

五、获取转换停止位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "123abc456";
    size_t pos;

    int n = stoi(s, &pos);  // pos 会记录停止位置

    cout << n << endl;      // 输出: 123
    cout << pos << endl;    // 输出: 3(在第3个字符处停止)

    // 剩余未转换的部分
    cout << s.substr(pos) << endl;  // 输出: abc456

    return 0;
}

六、异常处理

转换失败会抛出异常:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main() {
    try {
        int n = stoi("abc");  // 无效转换
    } catch (const invalid_argument& e) {
        cout << "无效参数: " << e.what() << endl;
    }

    try {
        int n = stoi("999999999999999999999");  // 溢出
    } catch (const out_of_range& e) {
        cout << "溢出: " << e.what() << endl;
    }

    return 0;
}

七、与 stringstream 对比

特点stoi/stodstringstream
头文件<string><sstream>
性能更快较慢
异常处理抛异常设置错误状态
进制转换直接支持需配合 hex/oct
灵活性单一转换可连续读取
本文由作者按照 CC BY 4.0 进行授权

热门标签