1. Homepage of Dr. Zoltán Porkoláb
    1. Home
    2. Archive
  2. Teaching
    1. Timetable
    2. Bolyai College
    3. C++ (for mathematicians)
    4. Imperative programming (BSc)
    5. Multiparadigm programming (MSc)
    6. Programming (MSc Aut. Sys.)
    7. Programming languages (PhD)
    8. Software technology lab
    9. Theses proposals (BSc and MSc)
  3. Research
    1. Sustrainability
    2. CodeChecker
    3. CodeCompass
    4. Templight
    5. Projects
    6. Conferences
    7. Publications
    8. PhD students
  4. Affiliations
    1. Dept. of Programming Languages and Compilers
    2. Ericsson Hungary Ltd

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 873

Later 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.