【问题标题】:Have a string as an integer [duplicate]将字符串作为整数[重复]
【发布时间】:2015-02-20 17:02:27
【问题描述】:
#include <iostream>
using namespace std;
int main ()
{
    string a;
    cin >> a;
    int b=10;
    cout << a+b;
    return 0;
}

上面的代码有问题。我知道这是错误的,但它表明了我的观点。

我想知道如果我得到一个数字作为字符串,我怎么能把它作为一个整数?比如我运行后给程序12。所以a 将是"12"。现在我想要 12 和变量 b 的总和。我应该怎么办?如何从字符串中提取 12 作为整数?

【问题讨论】:

标签: c++ integer extract


【解决方案1】:

上面提到的cmets,可以使用std::stoi

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string a;
    cin >> a;
    int b=10;
    cout << stoi(a)+b;
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 2010-11-21
    • 2013-10-06
    • 1970-01-01
    • 2011-07-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多