Monday, March 1, 2010

Dictionary Shortener

Recently, I had to write a program that shortened the dictionary. What I mean by this is that using a full dictionary (over 237,000 words), I needed to weed out the words that were longer than eight letters and shorter than three letters. I needed a list of letters between three and eight letters for an upcoming game that happens to need a dictionary to check against.

Why do I bring this up? Well, my program takes advantage of fstream, a coder's good friend or enemy, depending on your understanding of it.

In my next posting, I will show you the finer points of using fstream, but for now, here is the code for the dictionary shortening program:



#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
 
int main()
{
    string word;
    ifstream infile;
    ofstream outfile;
    int count=0;
    infile.open("fulldictionary.txt");
    if(infile.fail())
    {
        cout<<"File could not be opened\n";
        system("PAUSE");
        return 0;
    }
    outfile.open("dictionary_short.txt");
    if(outfile.fail())
    {
        cout<<"File could not be opened\n";
        system("PAUSE");
        return 0;
    }
    for(int i=0;!infile.fail();i++)
    {
        getline(infile,word);
        if(word.length()>=3&&word.length()<=8)
        {
            count+=1;
            cout<<count<<": "<<word<<endl;
            outfile<<word<<endl;
        }
    }
    infile.close();
    outfile.close();
    cout<<"There were "<<count<<" words saved in dictionary_short.txt\n";
    system("PAUSE");
    return 0;
}



The above code assumes that you have a file called "fulldictionary.txt" in the project folder and will automatically create the output file. There's no need to make that one.

2 comments:

  1. Pretty Neat Code Kiebler.
    "Efficiency is the Key to Success in Programming."

    ReplyDelete
  2. What? No multi-threading?
    Just kidding - very nice and simple.

    ReplyDelete