新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c++如何将string类型转换成int类型,c++如何将string类型转换成byte

发布时间:2023-10-27 18:04:04

c++如何将string类型转换成int类型

要将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类更灵活,可以用于更复杂的类型转换。