How to count number of occurrences of pattern within a string?

Program to calculate number of word / occurrences of a user-specified keyword?

  • I have made a program to calculate number of word and number of occurrences of a user-specified keyword. However it for the case 2, it keep giving the wrong input but if I choose case 2 first the output will be right... Why it that? I need to get both of the the correct input at the same time. Please check my code: #include <iostream> #include <fstream> using namespace std; int main ( ) { string fileName; cout<<"Which file do you want to open? "; cin >> fileName; ifstream inFile (fileName.c_str( ) ); if (!inFile) { cerr<<"No such file ."<<endl; exit(1); } int choice;int wordCount=0-1; string word; do { cout<<"===WELCOME==="<<endl; cout<<"1.Count the number of words."<<endl; cout<<"2.Count the number of keywords."<<endl; cout<<"3.Quit."<<endl; cout<<"Your choice: "; cin>>choice; switch (choice) { case 1: while (inFile) { inFile>>word; wordCount++; } cout<<"There were "<<wordCount<<" number of words in the file"<<endl; break; case 2: int key_wordcount=0;string word; string keyword; cout<<"Enter keyword: "; cin>>keyword; while (inFile) { inFile>>word; if(keyword==word) { key_wordcount++; } } cout<<"Number of occurences: "<<key_wordcount<<endl; break; } } while (choice!=3); system ("pause"); return 0; }

  • Answer:

    I'm not very good at C++ but I think you may need to close the file stream and re-open it between cases.

Cael at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

Place wordCount = 0; before switch (choice) because this variable is not initialized.

Art

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.