温馨提示×

c++ string库函数中字符串转数字的方法

c++
小樊
81
2024-09-24 22:27:11
栏目: 编程语言

在C++的string库函数中,可以使用std::stoi函数将字符串转换为数字。

std::stoi函数的原型如下:

int stoi(const string& str, size_t* idx = 0, int base = 10);

其中,str是要转换的字符串,idx是指向字符串中第一个非数字字符的位置的指针,默认为0,base是数字的基数,默认为10。如果字符串表示的是十六进制数,则base应该设置为16。

例如,将字符串"123"转换为数字:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "123";
    int num = stoi(str);
    cout << num << endl; // 输出123
    return 0;
}

如果字符串中包含非数字字符,std::stoi函数将抛出std::invalid_argument异常。可以使用try/catch语句来处理这种异常。

0