有什么函数能强制把字符串型(全是数字)转换成数值型

有什么函数能强制把字符串型(全是数字)转换成数值型?
之前用的atof( ),好像只能转字符数组(char型)。想转的是string型。

“Devil组”引证GPT后的撰写:
stoi() 函数将字符串型转换为整型。

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

int main() {
    string str = "1234";
    int num = stoi(str);
    cout << "num = " << num << endl;
    return 0;
}


stod() 函数将字符串型转换为双精度浮点型。

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

int main() {
    string str = "123.456";
    double num = stod(str);
    cout << "num = " << num << endl;
    return 0;
}


如果字符串中含有非数字字符,将会抛出 std::invalid_argument 异常。如果字符串中的数字超出了所需类型的范围,将会抛出 std::out_of_range 异常。

可以转,下面就将字符串str的每个字符单独转成数值temp_int

for(int i = 0;i<str.length();i++)    
{        
    char temp_char = str.charAt(i);       
    int temp_int = temp_char-'0';       //把字符转换成数字   
 
}