faqts : Computers : Programming : Languages : C++

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

37 of 62 people (60%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

I'm using Visual C++ and need to read a large text file, parsing it into separate words, and then place the words in a hash table. Any ideas?

Aug 30th, 2007 07:41
John Doe, Clay Dowling, Rafael Udaondo, Jim Bell,


You need to learn about the Standard Template Library.  Grab "The C++ 
Programming Language" by Bjarne Strouestrup (sp) and read it.
To solve your immediate problem, you might try something like this:
#include <map>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main( int argc, char **argv ) {
  if( argc == 1 ) {
    cerr << "Usage: " << argv[0] << " <file_to_proccess>." << endl;
    exit(1);
  }
  // This isn't really a hash, but the STL doesn't have a native hash
  map<string,int> count;
  string word;
  ifstream fin( argv[1] );
  while( fin >> word )
    count[word]++;
  map<string,int>::iterator iter;
  for( iter = count.begin(); iter != count.end(); iter++ )
    cout << "Word " << iter->first << " occurs "
         << iter->second << " times." << endl;
  return 0;
}
This solution will work in any modern C++ compiler, by the way.  Avoid 
the temptation to do things like use strtok and other standard C 
functions.  They'll get the job done, but it will be a lot more work 
than using the Standard Template Library, and much more prone to 
errors.