[Solved] Data File Handling – find count of word in file


The algorithm follows from what you have. Structure your while-loop like this:

while(!fin.eof()) {
    bool found = false;    
    do {
        fin.get(ch);
        found = found || ch == 'd';
    } while (ch == 'd' && fin);

    if (found && ch == 'o') {
        // boom goes the dynamite
    }
}

The purpose of the do-while is to eliminate repeating d‘s, so that after that loop, you simply check if the next character is o.

Note

  • In terms of typing, the type for ch should be char ch

Explained

  • while(!fin.eof())
    • Repeat the next few lines until we reach the end of the file
  • do {
    • Beginning of a do-while loop
  • fin.get(ch);
    • Read a single byte (character) from the file
  • found = found || ch == 'd';
    • Set found to true if we have already found a d or the current character is a d
  • } while (ch == 'd' && fin);
    • End of do-while. Repeat the loop until the last character read is not a d or we have reached the end of the file
  • if (found && ch == 'o') {
    • If we were able to satisfy the condition for setting found to true and the last character we read is o
  • // boom goes the dynamite
    • then we have successfully found the word do

Sans std::ios::eof

I won’t explain this next bit, but it will follow closely with what I already posted. The goal here is to protect yourself from reading an already empty file.

while(fin >> ch) {
    while(ch == 'd' && fin.get(ch)) {    
        if (ch != 'd') {
            if (ch != 'o') {
                break;
            }
            // Found it!
        }
    }
}

8

solved Data File Handling – find count of word in file