温馨提示×

C++里atoi转换字符串的技巧

c++
小樊
87
2024-08-23 11:37:26
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用std::stoi函数来将字符串转换为整数。std::stoi函数接受一个字符串作为参数,并返回相应的整数值。例如:

#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    int num = std::stoi(str);
    
    std::cout << "The integer value is: " << num << std::endl;
    
    return 0;
}

另外,如果需要将字符串转换为浮点数,可以使用std::stof或std::stod函数,具体使用方法与std::stoi类似。

需要注意的是,如果字符串无法转换为相应的数值类型,这些函数将抛出std::invalid_argument异常。因此,在调用这些函数之前,最好使用try-catch块来捕获异常。

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

推荐阅读:c++遍历字符串的技巧

0