c++怎么将string类型转换成int类型

c++
212
2023/10/15 18:04:04
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要将string类型转换为int类型,你可以使用C++的内置函数stoi()或者stringstream类来实现。

  1. 使用stoi()函数:
#include <iostream>
#include <string>

int main() {
    std::string str = "123";
    int num = std::stoi(str);
    std::cout << num << std::endl;
    return 0;
}
  1. 使用stringstream类:
#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string str = "123";
    std::stringstream ss(str);
    int num;
    ss >> num;
    std::cout << num << std::endl;
    return 0;
}

这两种方法都可以将string类型的变量转换为int类型,但是使用stoi()函数更简单直接,而stringstream类更灵活,可以用于更复杂的类型转换。

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

推荐阅读: c++ decltype推导规则是什么