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

c++
1161
2023/11/30 9:45:12
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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异常。因此,在实际使用中,需要进行异常处理。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++时间戳转字符串怎么实现