15,120,883 members
See more:
So, I have a small coding problem that has one minor thing that needs fixing
Basically you prompt the user to input an integer, and it outputs the sum as well as the individual digits.

So, it goes like this. If you input 123 it should output "1 2 3" and return a sum of 6
The problem is the code will output the numbers in reverse. I.e if I input 789 it will output 9 8 7. The sum output works just fine however. Just that little thing I need help with. The code's down below. I'm looking for another perspective on it :)
C++
```#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
//hold the number input, number and sum
int num_input, sum, num, pwr;

cout << "Enter a number" << endl;
cin >> num_input;

num_input = abs(num_input); //handle the negative numbers
sum = 0;

do
{

num = num_input % 10;
sum += num;
num_input = num_input / 10;
cout << num << " ";

} while (num_input > 0);

cout << "The sum of the numbers are: " << sum << endl;
}```

What I have tried:

Using arrays, while loops, for loops, vectors
Posted
Updated 5-Oct-21 18:48pm

One simple way would be to print it in the reverse order; use stack?

## Solution 1

If you know how to use `std::vector` you should also know how to reverse iterate over it using `rbegin()` and `rend()`. Put the digits of the number in a `vector<int>`, then use a `for()` loop with reverse iterators to print the digits. Or, you could use `reverse()` from the algorithms header on the vector. Or convert the number to an string, reverse it, and print the chars one by one.
v2

## Solution 2

Quote:
The problem is the code will output the numbers in reverse. I.e if I input 789 it will output 9 8 7.

The modulo (%) operator gets digits from right to left but you want digits from left to right.
If you handle input as an integer:
- To reverse the list of digits, you can use an array, a stack, a vector ...
- You can also use a recursive function to treat the input.
:You can also handle the input as a string
- and treat each char of the string individually.