Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::stoi missing in g++ 4.7.2?

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.

like image 605
AerosolSP Avatar asked Feb 07 '13 05:02

AerosolSP


People also ask

What library is std :: stoi in?

std::stoi is actually declared in <string> . Also, it was introduced in C++11, so that might be the problem. Don't mix C and C++ headers; use <cstdlib> instead. std::stoi is a standard library function, not a keyword.

What does stoi return?

Since stoi returns the integer value if parsed you can't directly use the return value to check for correctness. You could catch std::invalid_argument exception but it could be too much.

What is the difference between Atoi and stoi?

First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.

What exception does stoi throw?

The standard stoi function ignores extra spaces at the beginning or end of a string. This error says that the program stopped unexpectedly due to an invalid_argument exception thrown by the stoi function. The problem is that stoi can't convert “two” to an int .


1 Answers

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
like image 200
CanadaRox Avatar answered Oct 21 '22 10:10

CanadaRox