5

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!

John Yad
  • 123
  • 1
  • 1
  • 6
  • Why can't you use C++11? (Just curious) – wingerse Dec 24 '14 at 17:26
  • I want to, but the thing is, I am practicing problems on an online website, and it doesn't accept C++11. So, I am forced to use C++98 only. That is why. – John Yad Dec 24 '14 at 17:29
  • I strongly suggest you to use some good book such as C++ Primer. Most compilers suggest C++11. It will really make your life easier. See this: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – wingerse Dec 24 '14 at 17:34

4 Answers4

14

Convert it into a C string and you're done

string s;

int i = atoi(s.c_str());
Matteo Pacini
  • 21,796
  • 7
  • 67
  • 74
  • 3
    @JohnYad If you think this is the best answer, accept t by clicking on the tick on the left side of the post – wingerse Dec 24 '14 at 17:43
0

Use instead

int i = atoi( s.c_str() );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

There are also strtol(), and strtoul() family of functions, you might find them useful for different base etc

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64
0
// atoi_string (cX) 2014 adolfo.dimare@gmail.com
// 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
     }
 }
Adolfo
  • 281
  • 2
  • 5