tags:

views:

85

answers:

1

Suppose I would like to count characters in some mFile like this:

  while((c = getc(mFile)) != EOF){
    chars[c]++;
  }

If I try to show them:

  for(int f=0;f<256;f++) {
    if(isprint(f) && chars[f]>0) 
      cout << (char)f << " " << (int)chars[f] << endl;
  }

All characters print fine. But if I do

      cout << " " << (int)chars[32] << endl;

Then it doesn't print the number... just some large int, I guess, because it's negative. What am I doing wrong? Does getc break on, or not count spaces?

Thanks

+5  A: 

Based on your answer to my comment, I'd say the problem is likely to be that char is signed on your platform, and you have more than 127 spaces in your input file, so chars[32] is wrapping and becoming negative.

Why not use a more appropriately-sized type for your counters?

Oli Charlesworth
Exactly. Just because the OP's counting chars, that's no reason to store said counts in char variables.
Bob Kaufman