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