c++ - Data File Handling - find count of word in file -


i have homework question:

write function in c++ count presence of word 'do' in text file.

what have tried:

i tried first search word 'd' in text file, search 'o' if present after it.

#include <iostream> #include <fstream>  using std::fstream; using std::cout; using std::ios;  int main() {     char ch[10];     int count=0, a=0;     fstream f;     f.open("p.txt", ios::in);      while(!fin.eof())     {         fin.get(ch)         if (ch[a]=='d')         {             if ((a++)=='o')                 count++;         }          a++;     }     cout << "the no of do's is" << count;     f.close(); } 

but idea useless. cannot think of other ideas. love have hint regarding in 2 scenarios:

1.count word 'do' independently existing.

2.count word 'do' present anywhere in text.

this data file handling question.

the algorithm follows have. structure while-loop this:

while(!fin.eof()) {     bool found = false;         {         fin.get(ch);         found = found || ch == 'd';     } while (ch == 'd' && fin);      if (found && ch == 'o') {         // boom goes dynamite     } } 

the purpose of do-while eliminate repeating d's, after loop, check if next character o.

note

  • in terms of typing, type ch should char ch

explained

  • while(!fin.eof())
    • repeat next few lines until reach end of file
  • do {
    • beginning of do-while loop
  • fin.get(ch);
    • read single byte (character) file
  • found = found || ch == 'd';
    • set found true if have found d or current character d
  • } while (ch == 'd' && fin);
    • end of do-while. repeat loop until last character read not d or have reached end of file
  • if (found && ch == 'o') {
    • if able satisfy condition setting found true , last character read o...
  • // boom goes dynamite
    • then have found word do

sans std::ios::eof

i won't explain next bit, follow closely posted. goal here protect reading empty file.

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

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -