Reputation: 125
This is a basic question. I use C++ but not C++11. Now, I want to convert a string to an integer. I have declared like this:
string s;
int i = atoi(s);
However, this shows an error that such a conversion is not possible. I checked out the internet and I found that C++11 has stoi() but I want to use atoi itself. How can I do it? Thanks!
Upvotes: 5
Views: 15871
Reputation: 339
// atoi_string (cX) 2014 [email protected]
// http://stackoverflow.com/questions/27640333/
#include <string>
/// Convert 'str' to its integer value.
/// - Skips leading white space.
int atoi( const std::string& str ) {
std::string::const_iterator it;
it = str.begin();
while ( isspace(*it)) { ++it; } // skip white space
bool isPositive = true;
if ( *it=='-' ) {
isPositive = false;
++it;
}
int val = 0;
while ( isdigit(*it) ) {
val = val * 10 + (*it)-'0';
}
return ( isPositive ? val : -val );
}
#include <cassert> // assert()
#include <climits> // INT_MIN && INT_MAX
#include <cstdlib> // itoa()
int main() {
char mem[ 1+sizeof(int) ];
std::string str;
for ( int i=INT_MIN; true; ++i ) {
itoa( i, mem, 10 );
str = mem;
assert( i==atoi(str) ); // never stops
}
}
Upvotes: 0
Reputation: 20120
There are also strtol(), and strtoul() family of functions, you might find them useful for different base etc
Upvotes: 0
Reputation: 22846
Convert it into a C string and you're done
string s;
int i = atoi(s.c_str());
Upvotes: 16