I\'m trying to learn c++ on my own and I\'ve hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and
Stack and recursion is overkill for this problem. Just store each digit into a string and then reverse it before output. You need to work out how to call reverse
with the string
members for this to work. for_each can be used to output each element of the string.
For extra credit (by virtue of conciseness and expressiveness), insert the number directly into an ostringstream and use that as the basis for your reversible string
.
My stringstream
version of this code is 5 lines long. Logic is:
for_each
.You can sum the digits using accumulate on the string, provide you account for the fact that int('1') != 1
. That's an extra two lines, to sum the digits and output the result.
The point is not that doing this via stack or recursion is BAD, it's just that once you get more familiar with the STL there are typically more elegant ways to do a job than the obvious. Implementing this using stack, recursion and any other ways you can think of makes a simple homework into a great real-world learning experience.
Here's the accumulate
code to sum the members of a string
consisting of decimal digits, for example:
#include
#include
std::string intString("654321");
int sum = accumulate(intString.begin(), intString.end(), 0) -
(intString.size() * int('0'));
EDIT: here's the full code, for comparative purposes:
ostringstream intStream;
int value(123456);
intStream << value;
string intString(intStream.str());
for_each(intString.begin(), intString.end(), [] (char c) { cout << c << endl; });
int sum = accumulate(intString.begin(), intString.end(), 0) -
(intString.size() * int('0'));
cout << "Sum is " << sum << endl;