HELP!!!

I am new to C++. I am currently taking intro to C++ and was given the assignment below. The code I wrote does not even make it through the While loop...what I am doing wrong?

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

[code]

#include <iostream>

using namespace std;

int main()
{
int num;
int sum;
int individual_digits;

cout << "Enter an integer of any digit and press Enter: " << endl;
cin >> num;


sum = 0;

while (num >= 0)
{
individual_digits = num % 10;

sum = sum + num % 10;
}


cout << "The numbers are " << individual_digits << " " << endl;
cout << "The sum of the digits are " << sum << endl;

system ("pause");
return 0;
}
while (num >= 0)
{
individual_digits = num % 10;

sum = sum + num % 10;
num/=10;
}
you have to add num/=10 in the loop
or it wiuld be an infinite loop if your input(num) is a positive integer
I tried the num/=10, but the program doesn't even make it past the input during compilation.
Hello,

One of the ways to do this, is first to catch your input into a string.
After that, you want to loop through the string and get every separate number.
1
2
3
4
5
string num = "5548888";
for (int x=0; x<num.length(); x++)
{
cout << int num[x] << endl;
}

Now it prints every number, however at this stage you are not able to sum the numbers up. Since the output is in string format and you want them to be interger. So first you have to find a way to convert them to interger, how you are going to do that, depends on your cpp version. Just google string to int conversion cpp.

After you've converted the strings to int, your program will look like this:
1
2
3
4
5
6
7
8
9
10
11
string num = "5548888";
int individual_digits
for (int x=0; x<num.length(); x++)
{
cout << int num[x] << endl;
//convert num[x] to an interger and assign it to individual_digits
sum =+ individual_digits //this will sum up all individual digits

}
// go out of the loop and print your sum
cout << sum << endl;

Thank you guys for your input, but this hasn't helped. I will find another way. Thanks again!
Topic archived. No new replies allowed.