c++: Write a recursive function to_number that forms the integer sum of all digi
ID: 3677533 • Letter: C
Question
c++: Write a recursive function to_number that forms the integer sum of all digit characters in a string. For example, the result of to_number("3ac4") would be 7.Hint: If next is a digit character ('0' through '9'), function is_digit(next) in header will return true. What I have does not work. Is there a way to fix it?
#include
#include
#include
using namespace std;
int to_number (string s)
{
//int isdigit();
if (s == " " || s.length() == 0) {
return 0;
}
char next = s.string::at(0);
if (std::isdigit(next) == true) {
return isdigit(next) + to_number(s.string::substr(1));
}
else {
return to_number(s.string::substr(1));
}
}
int main()
{
string s;
cout << "Enter string. ";
cin >> s;
cout << to_number << endl;
system("pause");
}
Explanation / Answer
#include <iostream>
using namespace std;
int to_number (string s)
{
//int isdigit();
if (s == " " || s.length() == 0) {
return 0;
}
char next = s.string::at(0);
if (std::isdigit(next) == true) {
return next-'0'+ to_number(s.string::substr(1));
}
else {
return to_number(s.string::substr(1));
}
}
int main()
{
string s;
cout << "Enter string. ";
cin >> s;
cout << to_number(s) << endl;
system("pause");
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.