将字符串作为整数

Have a string as an integer

#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?

如上评论所述,可以使用std::stoi.

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