# c++ problem from a book I'm working through

This is a discussion on c++ problem from a book I'm working through within the C++ Programming forums, part of the General Programming Boards category; I've been trying to teach myself C++ through a book I picked up but this problem has me stumped ( ...

1. ## c++ problem from a book I'm working through

I've been trying to teach myself C++ through a book I picked up but this problem has me stumped ( its not homework):

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6; output the individual digits of 8030 as 8 0 3 0; output the individual digits of -2345 as 2 3 4 5.

heres the code I have but it separates the digits out in reverse order:
Code:
```#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int num, n;
int sum = 0;
cout<<"Enter a number: "<<flush;
cin>>num;

while (num != 0)
{
n = num % 10;
num = num / 10;
sum = sum + n;
cout<<setw(2)<<n;
}
cout<<endl;
cout<<"The sum is "<<sum<<endl;
return 0;
}```

2. You could allocate a temporary std::string, and each time through your current loop, prepend the newer character in front of the contents of your temporary string. When done, then output your string.

3. Like Todd said, you need a loop, and I also think storing the numbers as a char array and using strlen() will help.

4. When splitting up numbers, you typically get the digits in reverse order, because you don't know in advance how many you'll get so you can't really start from the back.

The typical solution is to first create the backwards version and then reverse it.