1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include "dict.h"
using namespace std;
Dictionary::Dictionary(const string &filename)
{
ifstream in(filename, ios::in);
if (in.fail())
{
cout << "Error, file failed to open: "
<< filename
<< endl;
}
in >> wordNum;
in.ignore();
get_memory();
load_array(in);
sort_array();
}
string Dictionary::lookupDefinition( const string &word )
{
words_def key;
key.word = word;
words_def *resultPtr;
resultPtr = (words_def *) bsearch( &key, word_def_array, wordNum, sizeof(words_def), compare );
if (resultPtr!=NULL){
return (resultPtr->def);
} else {
return ("is not in this dictionary. Try a different word. ");
}
}
int Dictionary::compare( const void *vp1, const void *vp2 )
{
const words_def *p1 = (const words_def *) vp1;
const words_def *p2 = (const words_def *) vp2;
return (p1->word.compare(p2->word));
}
void Dictionary::sort_array()
{
qsort( word_def_array , wordNum , sizeof(words_def) , compare);
}
void Dictionary::load_array(ifstream &in)
{
for (int inc = 0 ; inc < wordNum ; ++ inc)
{
getline ( in, word_def_array[inc].word, ',');
getline ( in, word_def_array[inc].def);
}
in.close();
}
void Dictionary::get_memory()
{
word_def_array = new words_def[wordNum];
if (! word_def_array){
cout << "Failed to allocate memory." << endl;
exit( EXIT_FAILURE );
}
}
void Dictionary::forEach( WordDefFunc func, bool forward )
{
if (forward == true){
heading();
for ( int i=0; i<wordNum; ++i )
func(word_def_array[i].word, word_def_array[i].def) ;
} else {
heading();
for ( int i = wordNum -1 ; i >= 0 ; --i ) {
func(word_def_array[i].word, word_def_array[i].def) ;
}
}
}
void Dictionary::heading()
{
cout << left << setw(10) << "**Word**"
<< setw(30) << "**Definition**"
<< endl << endl;
}
Dictionary::~Dictionary()
{
delete [] word_def_array;
}
|