user3390252
user3390252

Reputation: 49

How to compare a word from a file with a list of words in another file for C++?

So I'm having trouble grabbing a word from document1 and comparing it to the list of words in document2. So when I run the program, the first word of document1 is comparing to the list of words of document2, but the next word in document1 isn't comparing to the list in document2. I'm not sure what the problem is... Does it have something to do with the .eof() function?

string typedString, actualString, document1 = "A.txt", document2 = "Dictionary.txt";
ifstream observeDoc, actualDoc;

observeDoc.open(document1);
actualDoc.open(document2);

while (observeDoc.is_open())
{
    while (true)
    {
        observeDoc >> typedString;
        if (observeDoc.eof()) break;
        cout << typedString << endl;

        while (true)
        {
            actualDoc >> actualString;
            if (actualDoc.eof())
            {
                actualDoc.open(document1);
                break;
            }
            cout << '\t' << actualString << endl;
        }
    }
    if (observeDoc.eof()) break;
}

observeDoc.close();
actualDoc.close();

OUTPUT:


outputDictionary

Upvotes: 0

Views: 252

Answers (2)

SHR
SHR

Reputation: 8313

You need to go back to the beginning of the file.

you can use: observeDoc.seekg(0,ios::beg);

A better solution is to read all the words of the 1st file to an object from type std::set<std::string>, and for each word in the 2nd file check for existence in the set. In this way you move just once on each file, and no need to rewind.

std::set<std::string> words;
observeDoc.open(document1); 
while (observeDoc >> typedString){
   words.insert(typedString);
}
observeDoc.close();

actualDoc.open(document2);
while(actualDoc >> actualString){
   if (words.find( actualString )!= words.end()){
     //word exists in observer doc!
   }
} 
actualDoc.close();

Upvotes: 3

taylorc93
taylorc93

Reputation: 3716

Your problem is that actualDoc isn't resetting properly at the end of your loops. Also, your loop syntax could be way cleaner. Try this:

string typedString, actualString, document1 = "A.txt", document2 = "Dictionary.txt";
ifstream observeDoc, actualDoc;

observeDoc.open(document1);
actualDoc.open(document2);

// Will stop when it reads in EOF
while (observeDoc >> typedString)
{    
    while (actualDoc >> actualString)
    {
        // Do your comparisons here
    }
    actualDoc.open(document2); //reset actualDoc to start from the beginning of the file
    // or, as @SHR recommended, use observeDoc.seekg(0,ios::beg);
}

observeDoc.close();
actualDoc.close();

Upvotes: 1

Related Questions