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
}
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.
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