Exercise 1-11 (Test word count)

Chapter_1     Exercise_1-10     words Exercise_1-12







Exercise 1-11     K&R, p. 21


Exercise 1-11. How would you test the word count program? What kinds of input are most likely to uncover bugs if there are any?




Notes:

We have made nc a long (and can also be a float or double), as in K&R, p. 18. If there are very many short words in input, we can also make nw a long or float.
There are other whitespaces that can separate words, like '\f', '\r', '\v' (see Whitespace_character on Wikipedia). These can be added to the test if (c == ' ' || c == '\t').
We can test for boundary conditions, like an empty file, a file with only whitespace, with only one big word, a binary file, etc. (see Exercise_1-11 on clc-wiki-kr).





wordtest.c         download


#include <stdio.h> // for getchar(), printf(), EOF

#define IN 1
#define OUT 0

// counts chars, words, and lines

int main()
{
int c;
long nc = 0;
int nw = 0;
int nl = 1; // last line in a file ends with EOF, not '\n'
int state = OUT;

while ((c = getchar()) != EOF)
{
nc++;
if (c == ' ' || c == '\t' || c == '\f' || c == '\r' || c == '\v')
{state = OUT;}
else if (c == '\n')
{
nl++;
state = OUT;
}
else if (state == OUT) // not whitespace
{
state = IN;
nw++;
}
// else c is not whitespace and state == IN
}

printf("chars:\t%ld\n", nc);
printf("words:\t%d\n", nw);
printf("lines:\t%d\n", nl);
}
/*
gcc wordtest.c -o wordtest
./wordtest // input from keyboard
Hello!
What's up?
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
chars: 18
words: 3
lines: 3

./wordtest < wordtest.c // input from source file
chars: 1025
words: 182
lines: 58

./wordtest < wordtest // input from binary file
chars: 16008
words: 77
lines: 6
*/









Chapter_1     Exercise_1-10     words BACK_TO_TOP Exercise_1-12



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo