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.
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.
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With