扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c++字符串转数字怎么实现

扬州沐宇科技
2023-12-05 09:45:12
c++

在C++中,可以使用std::stoi函数将字符串转换为整数,使用std::stof函数将字符串转换为浮点数。

下面是一个示例代码:

#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    int num = std::stoi(str);
    std::cout << "转换后的整数为: " << num << std::endl;

    std::string str2 = "3.14";
    float num2 = std::stof(str2);
    std::cout << "转换后的浮点数为: " << num2 << std::endl;

    return 0;
}

输出结果为:

转换后的整数为: 12345
转换后的浮点数为: 3.14

需要注意的是,如果字符串无法转换为对应的数字类型,将会引发std::invalid_argument异常。因此,在实际使用中,需要进行异常处理。

扫码添加客服微信