C++: 将字符串或char转换为int [重复]

问题描述 投票:-1回答:1

如果我有。

string number = "45";

我怎么转 "45" 变成 45 作为一个整数?

我想能够做到这一点。

string number + 20 = 65
c++ string types int integer
1个回答
0
投票

您可以使用下面的例子 https:/en.cppreference.comwcppstringbasic_stringstol。:

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "45";
    std::string str2 = "3.14159";
    std::string str3 = "31337 with words";
    std::string str4 = "words and 2";

    int myint1 = std::stoi(str1);
    int myint2 = std::stoi(str2);
    int myint3 = std::stoi(str3);
    // error: 'std::invalid_argument'
    // int myint4 = std::stoi(str4);

    std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
    std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
    std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
    //std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
© www.soinside.com 2019 - 2024. All rights reserved.