std::stoi missing in g++ 4.7.2?

2019-01-23 16:35发布

I get the error message "stoi is not a member of std" when I try to use std::stoi and try to compile it. I'm using g++ 4.7.2 from the command line so it can't be IDE error, I have all my includes in order, and g++4.7.2 defaults to using c++11. If it helps, my OS is Ubuntu 12.10. Is there something I haven't configured?

#include <iostream>
#include <string>

using namespace std;

int main(){
  string theAnswer = "42";
  int ans = std::stoi(theAnswer, 0, 10);

  cout << "The answer to everything is " << ans << endl;
}

Will not compile. But there's nothing wrong with it.

2条回答
你好瞎i
2楼-- · 2019-01-23 16:54

For older version of C++ compiler does not support stoi. for the older version you can use the following code snippet to convert a string to integer.

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
    string input;
    cin >> input;
    int s = std::atoi(input.c_str());
    cout<<s<<endl;
    return 0;
}
查看更多
唯我独甜
3楼-- · 2019-01-23 17:02

std::stoi() is new in C++11 so you have to make sure you compile it with:

g++ -std=c++11 example.cpp

or

g++ -std=c++0x example.cpp
查看更多
登录 后发表回答