Exercise 2-3 (Count words in a file)
Chapter_2 Exercise_2-2 GetWords | Exercise_2-4 |
Exercise 2-3 TCP1, p. 120
Exercise 2-3. Create a program that opens a file and counts the whitespace-separated words in that file.
CountWords.cpp download
// Counts the whitespace-separated words in the file
#include <string>
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::string;
using std::ifstream;
int main()
{
int words = 0;
ifstream in("CountWords.cpp");
string word;
while(in >> word)
{words++;}
cout << "Number of whitespace-separated words: "
<< words << endl;
}
/*
g++ CountWords.cpp -o CountWords
./CountWords
Number of whitespace-separated words: 61
*/
Chapter_2 Exercise_2-2 GetWords | BACK_TO_TOP | Exercise_2-4 |
Comments
Post a Comment