2013-03-18 127 views
2

我在嘗試編譯下面的簡單程序時收到編譯錯誤。在使用ubuntu的C++中std :: stoi存在問題

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

我的目標是能夠在用戶輸入任何變量的垃圾時使用異常處理。

+1

它是C++ 11-only,所以用'-std = C++ 11'編譯。此外,'string.h'是C字符串頭,與'std :: string'無關。 – chris 2013-03-18 01:00:40

回答

5

如果你看看documentation,你會發現它是在C++ 11中引入的。您必須使用-std=c++11選項編譯代碼才能啓用這些功能,因爲默認情況下代碼不會編譯爲C++ 11。

德魯評論說,如果你使用的是C++ 03,可以使用

boost::lexical_cast<int>(buffer)

+0

相反,如果正在使用C++ 03,[boost :: lexical_cast](http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast.html)將是值得研究的。 – 2013-03-18 01:05:43

+0

@DrewDormann我很欣賞這個補充,我希望你不介意把它整合到我的答案中。 – 2013-03-18 01:06:41

+0

錯誤:無法識別的命令行選項'-std = C++ 11'我得到那個......我該如何編譯命令行來完成這項工作? – Matthew 2013-03-18 01:08:47

2

事實證明,我需要這一點是爲了它的工作...

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