Dictionary in C++ using File handling

I am now making a Dictionary using C++. My goal is to search the word and display the definition of the searched word from the text file. I have a code but it is not working.

How can I search a word and display the definition of the word from a text file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void searchFile(string word)
{
     ifstream ifile;
     ofile.open("dictionary.txt", ios::in);
     string line;
     string search;

    while(ofile.is_open())
    {
        getline(ifile, search);
        ifile >> search;
        if(word == search)
        {
            getline(ifile, search);
            cout << search << endl;
            ofile.close();
        }
        else
        {
            cout << "This definition does not exist." << endl;
            ofile.close();
        }
    }
}
Last edited on
You aren't paying close enough attention to what you are doing. For example, you open the open your "dictionary.txt" file for writing. (Why did you do that?) You never open the input file, but you try to read from it. You read only one word at a time from the file, but compare every possible word. So if your file looks like:

Amaze  v. (-zing) surprise greatly, fill with wonder.  amazement n. Amazing adj. [earlier amase from old english amasod]
Amazon  n. 1 female warrior of a mythical race in the black sea area. 2 (amazon) large, strong, or athletic woman.  amazonian adj. [latin from greek]
Ambassador  n. 1 diplomat sent to live abroad to represent his or her country's interests. 2 promoter (ambassador of peace).  ambassadorial adj. [latin ambactus servant]

Then if you search for surprise you might find the definition for "Amaze" and get something garbled after it.

Your search should read a line at a time, and compare the first word on the line with the word you are searching. You'll probably have to consider letter case. And any other specifics/disparities that the file format may throw at you.


If you plan to search more than one word, make yourself a dictionary (a std::map) that contains the word as a key and the location in the file of the definition as the value (see istream::ftell()).

If your dictionary is particularly large and you wish to minimize memory usage (this may be an issue if you are using a large dictionary), then only store the (word, file location) of every N-th word in the file, then use map::lower_bound() and map::upper_bound() to find the range in the file where the definition may lie.

I don't know anything about your dictionary file, but if multiple definitions for the same word are possible, you'll need to decide how to handle that as well.

Good luck!
Topic archived. No new replies allowed.