Exercise 2-4 (CountWord)
Chapter_2 Exercise_2-3 | Exercise_2-5 |
Exercise 2-4 TCP1, p. 120
Exercise 2-4. Create a program that counts the occurrence of a particular word in a file (use the string class' operator '==' to find the word).
CountWord.cpp download
// Counts the occurrences of a whitespace-separated word in the file
#include <string>
#include <iostream>
#include <fstream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ifstream;
int main()
{
int occurrences = 0;
string word, lookfor;
cout << "Word to look for in the file: ";
cin >> lookfor;
ifstream in("CountWord.cpp");
while(in >> word)
{
if (word == lookfor)
{occurrences++;}
}
cout << "Number of occurrences of '" << lookfor
<< "': " << occurrences << endl;
}
/*
g++ CountWord.cpp -o CountWord
./CountWord
Word to look for in the file: word
Number of occurrences of 'word': 2
./CountWord
Word to look for in the file: word,
Number of occurrences of 'word,': 2
./CountWord
Word to look for in the file: word)
Number of occurrences of 'word)': 2
./CountWord
Word to look for in the file: (word
Number of occurrences of '(word': 2
./CountWord
Word to look for in the file: ==
Number of occurrences of '==': 2
./CountWord
Word to look for in the file: >>
Number of occurrences of '>>': 3
./CountWord
Word to look for in the file: <<
Number of occurrences of '<<': 7
./CountWord
Word to look for in the file: occurrences
Number of occurrences of 'occurrences': 13
*/
Chapter_2 Exercise_2-3 | BACK_TO_TOP | Exercise_2-5 |
Comments
Post a Comment