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;
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.