Recursive function problems

I am studying for an upcoming exam and one of the questions on the study guide is:

Write a recursive C++ function for converting a string of digits into the integer it represents. For
example, “13531” represents the integer 13531. Your function should return the integer value.

I am able to convert the string to an integer but am having trouble on what the base case should be for the function to be recursive. Any suggestions or help would be much appreciated.
Empty (or one character) string.
This is a recursive function that does the opposite, and converts an integer into a string of digits:

1
2
3
4
5
6
7
8
9
10
11
12
std::string convert(int num)
{
    if (num == 0)
        return "";
    else if (num < 0)
    {
        num *= -1;
        return "-" + convert(num / 10) + static_cast<char>(num % 10 + '0');
    }
    else
        return convert(num / 10) + static_cast<char>(num % 10 + '0');
}


I guess it doesn't work if you're trying to convert 0 though.
Last edited on
Topic archived. No new replies allowed.