General Question about C++

So I am having a bit of difficulty with recursion. the part of my code that is sum += (num % 10 + sumDigitsOfString(num/10)); gives me an error which reads

//no suitable constructor exists to convert from "int" to //"std::__cxx11::basic_string<char, std::char_traits<char>, //std::allocator<char>>"

I honestly don't know what's wrong, so any helpful tips would be appreciative to fix this error or a workaround of some sort

// Recursive, Sums up digits from string to int
// Input: digits, string of numeric digits (no alphabetic characters!)
// Returns sum of numbers in digits

int sumDigitsOfString( string digits ) {
int sum = 0;
int num = stoi(digits);
if (num != 0) {
sum +=(num % 10 + sumDigitsOfString(num/10));
} else {
return sum
}

Last edited on
sumDigitsOfString is a function that accepts a string as parameter.

num/10 is not a string.

If you have an int, and you want a string representation of that, use std::to_string

1
2
3
4
5
6
7
8
int sumDigitsOfString( string digits ) {
int sum = 0;
int num = stoi(digits);
if (num != 0) {
sum +=(num % 10 + sumDigitsOfString(std::to_string(num/10)));
} else {
return sum
}


That function comes with the <string> header, so remember to #include that.

That said, this whole function would work better if it just accept an int as parameter. There's no reason to have strings involved here.
Last edited on
Honestly, that would be a lot easier I do understand that but my teacher is stubborn and wants us to pass a string into it

int sumDigitsOfString( string digits ) {
int sum = 0;
int num = stoi(digits);
if (num != 0) {
return sum += (num % 10 + sumDigitsOfString(to_string(num/10)));
} else {
return sum;
}
}

so I added to_string and nothing pops in the console
If you insist on passing strings ... there is no point in converting to or from an int ... anywhere!

Last digit is just the last char. Divisor by 10 is just the preceding substring.
Last edited on
nothing pops in the console


What does that mean? Does that mean it's working or it's not working? Is something meant to "pop" in the console?
@PhoenixKing3317,
Your code works fine as long as the int that you try to convert to ... is within the range of an int.

If you insist on doing anything bigger then you will need to avoid string-to-int and int-to-string conversions altogether.

Your teacher isn't necessarily stubborn. He/she may have set quite an interesting exercise.

Maybe you should tell us which strings you have tested it on. And post your full code. In code tags.
Last edited on
Topic archived. No new replies allowed.