views:

160

answers:

3

Simple "sum of digits" code. Compiles but when executed, the last cout gives a "0" for the num int rather than the actual user-input number.

Feel free to c&p into your own compiler, if you're so inclined, to see what I mean.

How can I get this to output the correct "num" value?

Thank you!

~~~

#include <iostream>

using namespace std;

int main()
{
  int num;
  int sum = 0;

  cout << "Please type any non-negative integer: ";
  cin >> num;

  while ( num > 0 ) {
    sum += num % 10;
    num /= 10;
  }

  cout << "The sum of the digits of " << num << " is " << sum << "\n";

  system("PAUSE");
  return 0;
}
+11  A: 

You've been modifying num all along until it becomes 0 (that's what your while ( num > 0 ) statement ensures!), so OF COURSE it's 0 at the end! If you want to emit what it was before, add e.g. int orig=num; before the loop, and emit orig at the end.

Alex Martelli
Correction: the while ensures `!(num > 0)`, not `num = 0`. You could end up with -100 if the user enters -100.
strager
Right -- if the user enters a negative number, it's going to stay untouched and similarly `sum` is going to remain zero. Not a particularly nice outcome, but then "it's impossible to build a foolproof system: fools are TOO ingenious!" -- defending against actively foolish user input is really an art more than a science;-).
Alex Martelli
Thank you Alex! Before I posted this question last night, I had been trying "num = orig" (the reverse of what you suggested) and I kept getting 84 as my orig value when I had it emit "orig" at the end. (BTW, why do you suppose *that* always the output I was getting in that case? No matter the input, it always gave "84" as the output.)In any event, your order works fabulously - thank you again!
+1  A: 

The problem is that num /= 10 changes num. If you want to get this to work, you should create a temp variable that you use to do all the calculations.

clahey
+1  A: 

For the next time, you can try to use a debugger. You'll find those "bugs" very easy!

Johannes