【问题标题】:C++: Convert string or char to int [duplicate]C ++:将字符串或字符转换为int [重复]
【发布时间】:2020-08-27 16:34:23
【问题描述】:

如果我有:

string number = "45";

如何将"45" 转换为整数形式的45

我希望能够做到这一点:

string number + 20 = 65

【问题讨论】:

  • std::stoi() 内置,可以使用
  • 试试std::stoi

标签: c++ string types int integer


【解决方案1】:

您可以使用https://en.cppreference.com/w/cpp/string/basic_string/stol中的以下示例:

#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';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 2013-03-02
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多