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 bechar 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
- Beginning of a
fin.get(ch);
- Read a single byte (character) from the file
found = found || ch == 'd';
- Set
found
to true if we have already found ad
or the current character is ad
- Set
} while (ch == 'd' && fin);
- End of
do-while
. Repeat the loop until the last character read is not ad
or we have reached the end of the file
- End of
if (found && ch == 'o') {
- If we were able to satisfy the condition for setting
found
to 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