I am totally new to C++, I studied assembler and C in college about 15 years ago and have worked with asp, dhtml, jscript, vbscript etc... over the years. So far all I have managed to do is gather together some 'training materials' and start at the beginning. One of the books I am starting with is Bruce Eckels 'Thinking in C++ Volume 1 (2nd Ed.)
So here's my question, at the end of chapter 2 he assigns a few exercizes
-Create a program that opens a file and counts the whitespace-separated words in that file.
-Create a program that counts the occurrence of a particular word in a file (use the string class’ operator ‘==’ to find the word).
Rather than do what he asked (my normal state is to do what I want) I decided to prompt the user for a file and a word to search for, then search the file replacing words with periods unless they match, count the matches, display which number word it is in the file that is matched, show total words, yada yada.
Would anyone care to take a look at the code and tell me if it could be cleaned up and what directions I might go in an effort to clean it up?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
vector<string> words;
string word, searchterm;
char filename[50];
int matchnum = 0;
int finalcount;
ifstream infile;
cout << "A Funky Word Searcher/Counter:" << endl << endl;
cout << "Enter the filename of the text file you wish to process:> " ;
cin.getline(filename, 50);
infile.open (filename);
cout << "Enter the word you wish to search/count:> " ;
cin >> searchterm;
if(!infile.is_open())
exit(EXIT_FAILURE);
cout << "You are searching for the word '" << searchterm << "' in the file '"
<< filename << "'" << "\n" << "\n" << endl;
system("pause");
while(infile >> word)
words.push_back(word);
for(int i = 0; i < words.size(); i++){
if (words[i] == searchterm)
cout << "\n" << "Word # " << i << ": '" << words[i] << "' match! # " << ++matchnum << endl;
else
cout << "." ;
finalcount = i;
}
cout << "\n" << "\n" << "\n" << matchnum << " total occurence(s) of " << "'"
<< searchterm << "'" << " in the file " << "'" << filename << "' out of " << finalcount << " total words." << endl;
cout << "\n";
system("pause");
return 0;
} ///:~
|
Cheers and Salutations to all, glad to have found this site and its resources.
Jahmbo