Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-12-05) 阅读数 9 #程序编程
文章标签 c++

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门