convert string into integer using recursion

This is a discussion on convert string into integer using recursion within the C++ Programming forums, part of the General Programming Boards category; this is my version and i do debug but the answer come out with 49 when i entered 123 as ...

  1. #16
    Registered User
    Join Date
    Jan 2006
    Posts
    141
    this is my version and i do debug but the answer come out with 49 when i entered 123 as string.

    Code:
    int convertRec(string num)
    {
        int n = num.length();
        int sum = 0;
        
        if(n == 1)
             return num[0];
        else
        {
            sum = sum * 10 + num[0];
            counter++;
            string number = num.substr(1,n);
            convertRec(number);
        }
        return sum;
    }
    can some one please help me to correct this code?

  2. #17
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,403
    1. Where is counter defined? And why are you incrementing it if you are not using it anywhere?

    Code:
    sum = sum * 10 + num[0];
    2. num[0] returns a char. That char is then converted to an int according to the character set you have in place. This almost always will give you the wrong result. '9' will not be converted to 9. Under the ascii set it will be converted to 57.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #18
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,403
    Ok... I took a second look at your code. Recursion can be tricky. But I think you are making it even trickier, Peter.

    First and foremost I suggest you read tutorials on recursion. Google is your friend here. Just use "c++ recursion tutorial" to get more than you can shake a stick at.

    Next, you need to approach recursion from a different angle, Peter. This is particularly true if you don't feel comfortable around it. And that angle is simply Divide and Conquer. Try to first create a working function that, while not using recursion, at least does what is asked of you. Have that function using a loop though.

    Why this helps? Because your function will have all elements needed to be converted into a recursive function; the loop, the stop condition and, obviously, the needed calculations.

    So... Let's start...

    Step 1. Make it work. Don't use recursion. Some examples were already given. here's one more:

    Code:
    double convertRec(std::string num)
    {
        double result = 0;
    
        for( size_t i = 0; i != num.size(); i++ ) {
            // we need the three elements for the formula number * base ^ exponent)
            size_t exponent = num.size() - 1 - i;
            double base = 10;
            int number = static_cast<int>(num[i]) - 48;
    
            result += number * pow(base, exponent);
    
        }
    
        return result;
    }
    Arguably, I could have not created so many variables. But I think this will help you understand better what is involved in converting the number. One note though: Look at the variable number. I'm converting num[i] (which returns a char) into an int. And then taking 48. This is because the ascii table which is almost certainly what your system will be using, places numbers 0 through 9 starting at ascii code 48. Of course... my solution is not necessarily portable. Other systems may use other character tables and render my magic number 48 useless. But let's not complicate things further. ASCII table it is.

    Step 2. Make it recursive.

    Now... we have fun. I'm obviously not going to spell it out for you in code. After all this is an assignment. But after you read those tutorials I bet you can see as clear as the day how you can convert the above into a recursive function.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  4. #19
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    If you're still stuck as to when to recurse, try this
    Code:
    #include <iostream>
    using namespace std;
    
    void pre_step ( int num ) {
         if ( num == 0 ) return;
         pre_step( num / 10 );
         cout << num % 10;
    }
    void post_step ( int num ) {
         if ( num == 0 ) return;
         cout << num % 10;
         post_step( num / 10 );
    }
    
    int main()
    {
        pre_step( 12345 ); cout << endl;
        post_step( 12345 ); cout << endl;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. convert from integer to string
    By peter_hii in forum C++ Programming
    Replies: 2
    Last Post: 04-06-2006, 09:28 AM
  3. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-26-2003, 11:03 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 10:06 PM
  5. please help ... to convert date to string
    By mel in forum C Programming
    Replies: 1
    Last Post: 06-12-2002, 10:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21