Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cin value returning 0 instead of the input value

Tags:

c++

Hi I am extremely new to c++. Working on an assignment where I need to add up all numbers of input then display the numbers next to eachother with the sum.

example:
input: 1234, output : 1 2 3 4 10

Here is my code so far:

#include <iostream>
using namespace std;

int main()
{
    int myNum;
    int total = 0;
    int digit;

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

    while(myNum >0)
    {
        digit =myNum %10;
        myNum/=10;
        total += digit;

    }
    while(myNum <0) {
        digit =myNum %10;
        myNum /=10;
        total +=digit;
    }

    cout << "The sum of digit is:" << myNum << total << endl;
    return 0;
}

The second while loop was to deal with negative numbers, but down on the cout when I put myNum to print the value I input it just prints 0 in front of the total, any reason the values aren't being carried over or how I could go about getting it to carry over?

like image 831
BBBBBBBBBBBBBBBBBBBBBBBBB Avatar asked Nov 22 '25 12:11

BBBBBBBBBBBBBBBBBBBBBBBBB


1 Answers

I updated the code to meet your original requirement. input:1234 output 1 2 3 4 10

The original code printed the myNum variable after using the /= operator repeatedly. The result will always be zero.

The requirements specify that each digit of the input must be printed as well as the total. In order to save the intermediate results, a vector is introduced. As each digit is produced it is pushed into the vector.

Once the input is exhausted, the individual digits and the total can be printed. The vector is traversed in reverse to print the digits in left to right order.

using namespace std;

int main(int arg, char*argv[])
{
int myNum;
vector<int> digits;

int total = 0;
int digit;

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

while(myNum >0)
{
    digit =myNum %10;
    myNum/=10;
    total += digit;
    digits.push_back(digit);

}
while(myNum <0){
    digit =myNum %10;
    myNum /=10;
    total +=digit;
    digits.push_back(digit);
}

for (auto it = digits.rbegin(); it != digits.rend(); ++it)
   cout << *it << " ";
cout << total << endl;
return 0;
}
like image 176
Matthew Fisher Avatar answered Nov 25 '25 01:11

Matthew Fisher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!