Converting strings into integers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Misko
    New Member
    • Aug 2007
    • 1

    Converting strings into integers

    Hi,

    I'm a newbie in the matter of C++.
    Now i'm trying to convert a text from a string (like str = "123") into an int-variable.
    In Java i've used parseInt for this function, but i can't find the C++-equivalence.
    I rather use a string and not a char-array...

    Idea someone?

    Thx in advance,
    Misko
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    Originally posted by Misko
    Hi,

    I'm a newbie in the matter of C++.
    Now i'm trying to convert a text from a string (like str = "123") into an int-variable.
    In Java i've used parseInt for this function, but i can't find the C++-equivalence.
    I rather use a string and not a char-array...

    Idea someone?

    Thx in advance,
    Misko
    Hi Misko,

    You can use atoi function for that.
    Usage is like this:

    int value = atoi ( const char * str );

    This requires char array as const char * is passed as a parameter.

    Regards

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      atoi() is deprecated in C++.

      Use a stringstream.
      [code=c]
      int result;
      string str("123");
      stringstream ss;
      ss << str;
      ss >> result;
      [/code]

      Comment

      • PieCook
        New Member
        • Jul 2007
        • 9

        #4
        I was just about to suggest a custom-made function, but the other ones look far better. I was going to do something like this:

        Code:
        int sum = 0;
        int length = strlen(str);
        for (i = length - 1; i >= 0; i--)
            sum += str[i] * pow(10, length - i);
        I did not run the code, so it might have a bug or two, but you get the idea.

        Comment

        Working...