Input an integer, output digits

I could use some guidance on this certain problem

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 4000 as
4 0 0 0, and the individual digits of -2345 as 2 3 4 5.

Here's my code so far

#include <iostream>
using namespace std;

int main (){
int num, n;
int sum = 0;
int rev = 0;
cout << "Enter any integer: ";
cin >> num;
if (num < 0)
num*=-1;
while (num > 0){
rev *= 10;
rev += (num % 10);
num /= 10;
}
cout << "The digits are: ";
while (rev!=0){
n = rev % 10;
rev /=10;
sum += n;
cout << n << " ";
}
cout << endl << "Sum of digits: " << sum << endl;
}

My problem is that when I enter an integer with trailing zeroes such as 4000, I only get the digit 4. I'm thinking it's because I set my num and rev so it won't operate with zero, but when I do, of course it'll just loop forever. Can anyone please help me with this?
Recommendation: Include math.h.

Then, you'll need a for or while loop that every iteration decreases a counter that starts at the length of the integer (character-wise, a logarithm, base 10, may be useful for determining this) and lets the loop repeat as long as it's above zero.

From there, you may wish to remember %pow(10,counter);

Other solutions may exist. Good luck.

-Albatross
You're over-analyzing the problem. Take a look at this code and see if you understand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main()
{
    int i;
    char ch[4];
    cout << "Enter a number to have it broken into digits: ";
    for(i=0;i<4;i++)
    {
        cin.get(ch[i]);
    }
    cout << "The numbers separate are: " << ch[0] << " " << ch[1] << " " << ch[2] << " "        
            << ch[3] << endl;

    return 0;
}
Eh... that's not the first time I've done something like that (figured out a very roundabout solution to a straight-forward problem). I can't even blame it on my programming in C too much, for using stdio.h, it would have been even shorter and more obvious.

-Albatross

EDIT: 2^8 posts and counting.
Last edited on
EDIT: 2^8 posts and counting.

Lol, I haven't seen that one used before.
Topic archived. No new replies allowed.