-4

I have a vector of a large text file that I open, and a search words file that I also open. I have two functions, isNextWord which checks if there is another word and the getNextWord which gets the next word.

I check if the search word is in the vector and then print out all the occurences at the end. My code works almost perfectly apart from the fact it skips the last word in the search word file.

For example if my words are: hello,these,are,my,search,words it will show all occurences apart from "words":

hello 5
these 2
are 5
my 7
search 9

This is my cpp file:

string ReadWords::getNextWord()
{
//gets next word of input from file

 return theword;

}


bool ReadWords::isNextWord()
{

return !eoffound;
}

This is my main

while (search.isNextWord()) {
        int occ= 0;
        string wordFound= search.getNextWord();
        for(int i=0; i < vct.size(); i++){
            if(vct[i] == wordFound) {
                occ++;
            }
        }


       cout << wordSearch <<  " " << occ<< endl;
    }

Why doesn't it perform the getNext word one last time?

  • 1
    Why not simply `while(wordfile >> wordFound)`? – user0042 Nov 17 '17 at 16:45
  • 1
    Also read this please: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user0042 Nov 17 '17 at 16:46
  • Well i wanted to use my isNextWord function if possible – beastcplusplus Nov 17 '17 at 16:46
  • What should be the advantage to use a separate function? – user0042 Nov 17 '17 at 16:48
  • Well its more along the lines of why mine doesn't work but that would. – beastcplusplus Nov 17 '17 at 17:00
  • _"why mine doesn't work but that would"_ Because `wordfile >> wordFound` returns the stream state while still reading the word, and not just the state of the `eof()` flag. – user0042 Nov 17 '17 at 17:02
  • Your code has logical error. While reading (through getNextWord()), you set the eoffound flag to be true _after_ reading the last word, and yet, when using (in your main()), you check the eoffound _before_ reading the words. You'll always lose the last word this way. – realharry Nov 17 '17 at 17:04
  • I see, but is there a way to use my `eof()` state and isNext? If it is a requirement. "There is always a way" i guess – beastcplusplus Nov 17 '17 at 17:04

1 Answers1

-1

You are activating the eof flag when it get the last word, then, the function ReadWords::isNextWord() returns false and the loop is out and the last word is never printed. For example, when the word search is returned, you read the last one and enable the flag.

I recommend change the function isNextWord to

bool ReadWords::isNextWord() {return !(wordfile.eof()); }