Thread: convert string into integer using recursion

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    141

    convert string into integer using recursion

    hi, can someone give me an idea on how to convert string to integer using array
    for example

    string n = '123';
    int c;

    cout<<c;

    and will display 123.

    what i think of is 123 divide by 10 or the second idea tat i have is

    for example: string s = 123

    |1|2|3|
    ---------
    0 1 2

    and

    s[n-1] = 3
    +
    s[n-2] = 2 * 10
    +
    s[n-3] = 1 * 100
    =
    123

    how can i start with?
    Code:
    int stringConIntRec(string number)
    {
            if(number.length() == 0)
                     return 0;
            else
            {
               ???????
                ???????
             }
    }

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    One way to look at it:

    0 * 10 = 0
    0 + 1 = 1
    1 * 10 = 10
    10 + 2 = 12
    12 * 10 = 120
    120 + 3 = 123
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    firstchar * 10 ^ depth + recursion(restofstring);
    depth can be tracked with length of string.

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Are you required to do it that way?

    Normally in C++ you'd use stringstream:

    Code:
    #include <string>
    #include <sstream>
    int main()
    {
        std::string s("123");
        int i;
        std::stringstream stoi(s);
        stoi >> i;  //voila
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Jan 2006
    Posts
    141
    hi Tonto, can u descrive what does '^' mean in your code please? sorry i am newbie of c++

  6. #6
    Registered User
    Join Date
    Aug 2003
    Posts
    127
    there is a c++ way,
    Code:
    template<typename _To, typename _From>
    _To lexcial_cast(_From from)
    {
        _To to;
        std::stringstream ss(from);
        ss>>to;
        return to;
    }
    
    int main()
    {
        std::string str = "123"
        int i = lexcial_cast<int>(str);
        str = lexcial_cast<std::string>(i/10);
    }
    Nana C++ Library is a GUI framework that designed to be C++ style, cross-platform and easy-to-use.

  7. #7
    Registered User
    Join Date
    Jan 2006
    Posts
    141
    this is my solution and seems like got some error... being looking and thinking but couldnt get it correct. can some one list the error..?

    Code:
    int convertRec(string num)
    {
        int y;
        
        if(num.length()==0)
            return num;
        else
        {
            int depth = num.length();
            int position = 0;
            int s = 4;
            
            y = (num[position] * 10 ^ depth) + convertRec(num.substr(depth-s, depth-10));
            s--;
        }
        return y;
    }

  8. #8
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Well, without looking at the actual recursion yet, I can tell you return num; will give you a compile error. You are trying to return a string from a function that returns an int.
    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.

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> 10 ^ depth
    Don't actually use ^. That doesn't mean to the power of in C++. Perhaps pow() is what you want.

  10. #10
    Registered User
    Join Date
    Jan 2006
    Posts
    141
    the power()? you mean power of deth?

    Code:
    int convertRec(string num)
    {
        int y;
        
        if(num.length()==0)
            return 0;
        else
        {
            int depth = num.length();
            int position = 0;
            int s = 4;
            
            y = pow(num[position] * 10, depth) + convertRec(num.substr(depth-s, depth-10));
            s--;
        }
        return y;
    }
    is this wat you mea DAVED

  11. #11
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    pow(num[position] * 10, depth)

    You have to cast num[position] into an int.
    Code:
    pow(static_cast<int>(num[position]) * 10, depth)
    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.

  12. #12
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    I'm not very good at looking at recursion. Always struggle with it. But I can tell you it will not work as it is.

    The problem is that you are not creating a stop condition. Something has to make the recursion to stop. Probably the var depth.

    You are not decremeting this value and my guess is that you should. With each call to the function you will want the base 10 exponent to decrease in order to produce the correct numbers 145 = 1*10^2 + 4*10^1 + 5*10^0.

    Also, I'm not sure what s is doing there. Isn't it the same as the result of lenght()? If it is, you don't want it, do you?
    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.

  13. #13
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    On each iteration, multiply the current value by 10 and add the next.
    Code:
    int stoi (string &s)
    {
    	int  num = 0;
    	int  i   = 0;
    	bool neg = false;
    
    	if (s[0] == '-') {
    		neg = true;
    		i++;
    	}
    	for (; i < s.length(); i++) {
    		if (s[i] >= '0' && s[i] <= '9')
    			num = num*10 + (s[i] - '0');
    		else
    			return -1;
    	}
    	if (neg)
    		return -num;
    	return num;
    }

  14. #14
    Registered User
    Join Date
    Jan 2006
    Posts
    141
    hi everyone, thank you for helping me but i really need to stick with recursion from converting string into integer.

    really appreciate all effort....

    hope can get some idea from others again...i am working on it as well...

  15. #15
    Registered User
    Join Date
    Aug 2006
    Posts
    11
    first you must have a function which converts character 1 to 9 to integer 1 to 9;

    try subtracting 48 to char but first you must store it to an integer variable

    Code:
    // assume you name this as num() function
    char s[n];
    int x=char s[n];
    int z=x-48;
    return z;
    then you can apply your idea:

    [tag]
    |1|2|3|
    ---------
    0 1 2

    and

    s[n-1] = 3
    +
    s[n-2] = 2 * 10
    +
    s[n-3] = 1 * 100
    =
    123
    [/tag]

    you need to do a program which first start a the first element(assume s[0]) which keeps on incrementing until it hits the end (s[strlen(s)]), and about the "x10" problem you must do a power fuction like this:

    Code:
     
    
    int power(int n){ //n is the number nth of the element (i.e. s[1] here n=1) 
    
    int x;
    
    for(x=0;x<n;x++){
    
    int z=z*10; (can be z*=10)
    }
    return z;
    using this functions you can now create a program that answers your problem recursively. (^^ sorry can't make the program right now but hope this helps)

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-27-2003, 12:03 AM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11: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