使用ubuntu在C++中使用std :: stoi的问题

Mat*_*hew 2 c++ string

我尝试编译下面的简单程序时收到编译错误.

error: ‘stoi’ was not declared in this scope

我试图将两者都包括在内#include <string>,#include <string.h>而且我仍然遇到这些问题.我正在使用Ubuntu,我不记得我是如何安装g ++的,但我确信它是使用apt-get install g ++命令,因此我不知道我使用的是什么版本的g ++或C++库.

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

struct Data
{
    string fname;
    string lname;
    int age;
};

int main()
{
    bool toContinue = true;
    Data data;
    string buffer;
    do
    {
        try
        {
            getline(cin,data.fname);
            getline(cin,data.lname);
            getline(cin,buffer);
            data.age = stoi(buffer);
            cout<<data.fname<<" ";
            cout<<data.lname<<" ";
            cout<<data.age<<endl;
        }
        catch(std::invalid_argument)
        {
            cerr<<"Unable to parse integer";
        }
    }while(toContinue);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的目标是能够在用户输入任何变量的垃圾时使用异常处理.

Jor*_*eña 5

如果你看看文档,你会发现它是在C++ 11中引入的.您必须使用-std=c++11启用这些功能的选项编译代码,因为默认情况下代码不会编译为C++ 11.

Drew评论说如果你使用C++ 03,你可以使用

boost::lexical_cast<int>(buffer)