0

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

Feel free to copy and paste this 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?

~~~

#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;
}
Ren
  • 1,111
  • 5
  • 15
  • 24
  • I removed the system("PAUSE"); and it seemed to work fine. http://codepad.org/bwpGuJF8 (mind you codepad does not allow you to enter an input). The error I was getting before was this: Disallowed system call: SYS_fork – Tom Sep 05 '09 at 04:32
  • system("PAUSE") is a windows specific thing, on most (some?) unix machines it will try to feed that to the default shell. A better way to get the desired behavir is to call cin: cout << "Enter any key\n"; int wait; cin >> wait; – Dan O Sep 05 '09 at 08:02

3 Answers3

11

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
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    Correction: the while ensures `!(num > 0)`, not `num = 0`. You could end up with -100 if the user enters -100. – strager Sep 05 '09 at 05:48
  • 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 Sep 05 '09 at 05:52
  • 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! –  Sep 05 '09 at 13:43
1

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
  • 4,795
  • 3
  • 27
  • 20
1

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

Johannes
  • 23
  • 5