Hi I was wonder if anyone could help with this problem I am receiving. My program is suppose to read in any character frequencies from a file, even spaces and /n. My problem is that is reading an extra character that I can figure out.
I had inputed a text file that aab no spaces and no new lines. It would out put as
The Character Frequencies are
1
a 2
b 1
which throws everything off.
This program will make a huffman code out of the frequencies, but it messes up everything cause of the unknown space and 1. Here is what I've been using for my read input. If anyone could take a look I would really appreciate it.

#include <cstdio>
#include <fstream>
#include <iostream>
#include <cstring>
//tab space 1
using namespace std;


void phase1(int array[], ifstream& in)
{
  int c = 0;  
  for(int i = 0; i < 255; i++)
  {
  	array[i] = 0;
  }
  while(c != EOF)
  {
    c = in.get();
    c = (int)c;
    array[c] = array[c]+1;
  }
}

//phase2 prints the frequency of each character
//read from a text file
void phase2(int array[])
{
  int n = 0;
  
  cout << "The character frequencies are: " << '\n';
  
  while(n < 255)
  {
    if(array[n] != 0)
    {
      cout << (char)n; 
      cout << " ";
      cout << array[n];
      cout << "\n";
    }
    n = n + 1;
  }
}

int main(int argc, char* argv[])
{
  ifstream in(argv[1]);
  int array[256];
  phase1(array, in);
  phase2(array);
  return 0;
}

it will read in some imaginary output I guess is the best way the say it.
Since there are no spaces or new lines, its reading something that it shouldn't
that's why I get
1
a 2
b 1
does that make sense?

In your function phase1 you've to change everything in the while loop to:

c = in.get();
/* We use an if-statement to ignore the newlines */
if(c != '\n')
{
        c = (int)c;
	array[c] = array[c]+1;
}

It should work now !

If I were to make this, I wouldn't use array's, but I'd use a map:

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main(void)
{
    //store
    string str = "aab";
    map<char,int> total;
    for (unsigned i =0; i < str.size(); i++)
        total[str[i]] += 1;
    //show   
    map<char,int>::iterator it;
    for (it = total.begin(); it != total.end(); ++it)
        cout << "'" << it->first << "': " << it->second << " times\n"; 
    return 0;
}

nice and simple :)

This article has been dead for over six months. Start a new discussion instead.