Search code examples
cio

K&R Chapter 1.5.4: "How would you test the word count program?"


Beginner here.

In the ANSI C textbook by K&R, page 20, they ask: How would you test the word count program?

I have copied exactly from the text book, using the CodeBlocks IDE, console application. I have seen many great input tests online, but my question is even dumber. How do I actually input something? Nothing happens when I press enter. Do I have this problem because I am using an IDE and therefore not learning how to run C programs properly? Thanks in advance. I added a picture to show you what I mean

Here is the code:

#include <stdio.h>

#define IN 1    /* inside a word */
#define OUT 0   /* outside a word */

/* counts lines, words and characters as input */

main()
{
    int c, nl, nw, nc, state;

    state = OUT;
    /* set these three constants to 0: */
    nl = nw = nc = 0;
    while ((c = getchar()) != EOF){
        ++nc;
        if (c == '\n')
            ++nl;
            /* || == OR (&& == AND)
            evaluation of the following line
            will stop as soon as the truth or
            falsehood is known, so the order matters */
        if (c == ' ' || c == '\n' == c == '\t')
            state = OUT;
        else if (state == OUT){
            state = IN;
            ++nw;
        }
    }
    printf("%d %d %d\n", nl, nw, nc);
}

Solution

  • The program to count words in K&R 2nd edition is made to run on an environment in which you signal the end of input somehow. Normally, as they used UNIX all the time, they used Ctrl-D sequence (which is valid if you run the program in Linux or any Unix-like operating system) This has been so since the early beginning of the UNIX system.

    Windows signals the end of input in a console application by the input of a Ctrl-Z (probably followed by a keyboard return key)

    If you redirect the input from a file (as when you say a.out <my_input_file.txt) you'll get the number of words at the end, when there's no more input in the file.

    You are running the program in an IDE, which is something that normally hides you where standard input and standard output go, or how to signal the window you show how to say that there's not more input to the program.

    For the program to get to it's end, you have first to know how to get to an end on input.