Practice 4.
wcount
Write a program which works similary to the wc Unix utility: counts the number of newlines, words and characters of the input. In this simple case, the input is the standard input std::cin.
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
//
// wcount -- similar to unix wc command
// counts newlines, words and characters
// v1. reading from standard input
//
#include <iostream>
#include <cctype> // for std::isspace
int main()
{
int lcount = 0; // newlines
int wcount = 0; // words
int ccount = 0; // characters
char ch; // current character to read in
char prev = '\n'; // previous char for wcount initialized
// to whitespace for the very first
// word at the beginning of the input
std::cin >> std::noskipws; // otherwise operator>>
// skips the whitespaces
while ( std::cin >> ch ) // true until reading fails
{
++ccount;
if ( '\n' == ch ) ++lcount; // put the literalt on left
if ( std::isspace(prev) && !std::isspace(ch) ) ++wcount;
prev = ch;
}
std::cout << lcount <<" "<< wcount <<" "<< ccount <<'\n';
return 0;
}
The program can be tested for various inputs. The output is checked against the wc Unix utility.
$ g++ -Wall -Wextra wcount.cpp -o wcount
$ ./wcount < wcount.cpp
31 146 873
$ wc < wcount1.cpp
31 146 873Later in Practice 12 this program will be further developed to accept command line arguments as filenames and write out a summary line if there were more arguments.
Financed from the financial support ELTE won from the Higher Education
Restructuring Fund of the Hungarian Government.