11

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
AerosolSP
  • 177
  • 1
  • 1
  • 10

2 Answers2

16

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
CanadaRox
  • 300
  • 2
  • 5
  • 7
    Does not work either. Besides, -std=c++11 appears to be enabled by default. One of my compiler warnings for the code I'm working on says as much (note, the code above simply tells me the stoi is not a member of stoi,so the problem isn't with my code). – AerosolSP Feb 07 '13 at 05:33
  • I saved your code as example.cpp and tried: `g++ example.cpp` and got the error you mentioned. When I added either `-std=c++11` or `-std=c++0x` it compiles and runs just fine. The g++ man page on my laptop says that gnu++98 is the default dialect for C++. – CanadaRox Feb 07 '13 at 05:42
  • 3
    Scratch all that. Now I know why it wasn't working. The flag has to be set before you specify the filename of the source code to be compiled...wasn't aware of that and I didn't see anything that pointed that fact out anywhere. Case closed. – AerosolSP Feb 07 '13 at 06:04
  • That is news to me as well, glad you got it sorted out! – CanadaRox Feb 08 '13 at 07:41
  • what do you mean by 'flag has to be set"??? what flag? im stuck on a similar problem – Mohsin Oct 29 '16 at 02:23
4

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;
}
BeingMIAkashs
  • 1,375
  • 11
  • 18