1

I'm doing a character count via char c = cin.get(). Example of my output would be: a: 53 b: 32 c: 29 etc..

For one of the alphabets, I'm getting an insanely large 9-digit number. And then when I use another input file that has more characters, the numbers are 6-digits and too large to be accurate. Any thoughts of this phenotype?

Again, sorry it's crunch time with the end of the semester. I appreciate any help out there.

int main (int argc, char *argv[])
{

int count [26] = { };   
char alpha [26] = { };

char c;

c = cin.get();     
while(!cin.eof())
{
  if (isalpha(c))
  {
  c = tolower(c);      
  }    

  count [ c - 'a']++;
  alpha [ c - 'a'] = c;

  c = cin.get();
  }     

  for ( int i = 0; i<26; i++ )
     {
     cout << alpha[i] << ":" << count[i] << endl;
     } 

  } //end main    

Here's the output: (edited)

a:224
b:50
c:70
d:20
e:167772180
f:10
g:40
h:66
i:28

Here's the input: (edited)

aaaaaaaaAAAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAAAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaBBBB

Made these changes, but it's still "hanging":

c = cin.get();     
while(c=cin.get())
{
  c = tolower(c);
  if (isalpha(c))
      continue;      


  count [ c - 'a']++;
  alpha [ c - 'a'] = c;

  }     

  for ( int i = 0; i<26; i++ )
     {
     cout << alpha[i] << ":" << count[i] << endl;
     } 

  } //end main    
harman2012
  • 103
  • 2
  • 8

1 Answers1

4

If the input file contains anyting else than letters, anything can happen because you are accessing the array wtih out of bounds indices. Maybe you meant:

while(!cin.eof())
{
    if (isalpha(c))
    {
        c = tolower(c);      

        count [ c - 'a']++;
        alpha [ c - 'a'] = c;
     }

    c = cin.get();
}     

E.g. when your data contains a line feed character (10) you are accessing alpha with index 10 - 97 = -87. And this probably writes 10 into the most significant byte of count[4].

Henrik
  • 22,652
  • 6
  • 38
  • 90
  • Did you mean `(isalpha(c))`? – harman2012 Nov 30 '12 at 08:33
  • @harman2012 - just realized that `continue` would also skip the `cin.get()` at the end of the loop. Edited my answer. – Henrik Nov 30 '12 at 08:38
  • Yes, the new line makes sense! Although looking at the file, a new line is returned at "s". I will scrutinize this new discovery. So the smaller file works and that makes sense to put the counts under isalpha(). Thanks so much! – harman2012 Nov 30 '12 at 08:54