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
Other answers
Place wordCount = 0; before switch (choice) because this variable is not initialized.
Art
Related Q & A:
- How To Calculate The Value Of PI With A Program?Best solution by social.msdn.microsoft.com
- How to check on all the permissions granted to a user and apply the same permissions to another user?Best solution by Stack Overflow
- How do I permanently block a user forever? I mean, find or enter the username, when the user isnt on my list?Best solution by Yahoo! Answers
- Is "potent" a good word to describe a leader?Best solution by yourbusiness.azcentral.com
- Changing a user on a BlackBerry?Best solution by supportforums.blackberry.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.