class Dictionary
{
private:
list<string> dictionary;
public:
//CONSTRUCTORS
Dictionary();
Dictionary(const string& fileName);
}
//Opens file & stores words in a file dictionary
//If file doesn't open then an exception is thrown
Dictionary::Dictionary(const string& filename)
{
Dictionary x;
//Opens the file
ifstream iFile( filename.c_str() );
string words;
//Check to see if it opens
if( !iFile.is_open() )
{
cerr<< "at Dictionary::Dictionary(): File couldn't oepn. \n";
return;
}
//Reads all word from file
while (true)
{
if( iFile.eof() ) break;
x.addWord(words);
}
}
void Dictionary::addWord(const string& str)
{
for(list<string>::iterator it = dictionary.begin(); it!=dictionary.end();it++)
{
if(*it==str){
return;
}
}
dictionary.push_back(str);
}
int main()
{
string filename = "words.txt";
Dictionary diction;
diction.Dictionary(filename);
//I have also tried doing this:
//Dictionary diction = Dictionary(filename);
//But that gives me a blinking cursor with no end
}
You now need to start adding code in the constructor to lad words into the list. And that could look something (rough and ready as it is) like this, or a separate addWord() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Dictionary::Dictionary(const std::string afilename)
{
file_name = afilename;
std::string word;
std::ifstream myfile (file_name);
if (myfile.is_open())
{
while ( myfile >> word )
{
dictionary.push_front(word);
}
myfile.close();
}
else std::cout << "Unable to open file";
}
BTW <maps> are better suited to dictionaries than <lists>, but up to you.
iFile.eof() will always be false since you don't read anything from it, so the file pointer doesn't change, causing EOF never being reached. You can use a string to store every line (using getline(iFile, line)) and split them by whitespace (I guess you want the words) and push them to the dictionary.
Line 13: The comment is incorrect. No exception is thrown. You exit the constructor, but your code continues.
Line 16: You're creating a local instance of Dictionary called x. This local variable goes out of scope at line 36, thereby losing everything you've added to it.
Lines 30-34: You're going to have an infinite loop here. You never read from ifile, therefore you will never reach eof.
Line 34: You should be adding to the list called dictionary (line 4). Not the best choice of a name for the list. Not x. x does not have an addword() member function declared. You should be calling your addword() function (not qualified by x).
Line 39: You have no declaration for addword() in your class declaration.
Line 55: You're instantiating Dictionary using its default constructor, but you have no implementation of Dictionary's default constructor.
Line 57: This is not the proper way to invoke your filename constructor.