Outputting digits of an integer separetely.

Hi, the program I am working on in my spare time is supposed to take as an integer a number and output the digits of the number separately as well as the sum of the digits. I am able to output the sum but am struggling with outputting the digits separately. (I tried storing the digits as chars, but when i do that the sum is messed up because the sum is an int, and 7+'7'==14 is false).. Here is my code thus far. Any evaluation is greatly appreciated!!

int main()
{
int num, sum=0, digit, temp, a=1, k;


cout << "Enter a number: ";
cin >> num;
temp=num; // variable to hold the number.
k=temp; //variable to hold the number.

while(temp>0)
{
digit=temp%10; // Extract the last digit from temp and store it in digit.
sum=sum+digit; // Once you get the digit, add it to the sum.
temp=temp/10; // Update temp by removing the last digit, so you don't add already used digits again.

/* This loop gives the number of digits in num,
which is represented as the variable a. */
for(a;k/10!=0;a++)
k=k/10;

}


cout << endl;
cout << sum << endl;

return 0;
}
Last edited on
store the individual digits in a vector: http://www.cplusplus.com/reference/stl/vector/
You can't directly type cast an integer to a char as the ASCII code for the character '7' NOT the number 7 (you can look up the real value in an ASCII table).

Just as an alternative rather than holding the individual integers in a vector you could also store them in an integer array and output them to the same effect.

An alternative method could be to convert the integer to a string. You can do this by using the function itoa BUT it's not really C++ but it's supported by some compilers so beware.

Heres the link to itoa: http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

An alternative to this could be to use the function sprintf which is a C function.

Link to sprintf: http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Once you have the integer in string format you can display it one character at a time, using various methods ( string::at(...), ect. ).
Topic archived. No new replies allowed.