简体   繁体   English

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

[英]Problems with std::stoi in C++ using ubuntu

I am receiving a compile error when I try to compile the simple program below. 我尝试编译下面的简单程序时收到编译错误。

error: 'stoi' was not declared in this scope

I've tried to include both #include <string> and #include <string.h> and I still am having those issues. 我试图包括#include <string>#include <string.h> ,我仍然遇到这些问题。 I am using Ubuntu and I cannot remember how I installed g++ but I am sure it was using the apt-get install g++ command, so I do not know what version of g++ or the C++ libraries I am using. 我正在使用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;
}

My goal is to be able to use exception handling in case the user enters junk for any of the variables. 我的目标是能够在用户为任何变量输入垃圾时使用异常处理。

If you take a look at the documentation , you'll see that it was introduced in C++11. 如果您看一下文档 ,您会发现它是C ++ 11中引入的。 You'll have to compile your code with the -std=c++11 option to enable those features because code isn't compiled as C++11 by default. 您必须使用-std=c++11选项编译代码才能启用这些功能,因为默认情况下代码不会编译为C ++ 11。

Drew commented saying that if you are using C++03, you can use Drew评论说如果你使用C ++ 03,你可以使用

boost::lexical_cast<int>(buffer)

事实证明我需要它才能使它工作......

g++ -std=c++0x ./main.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM