Harshit Jindal
Harshit Jindal

Reputation: 621

Modification of C code to process the input provided

Introduction: I'm a beginner in C programming and my guide recommended 'The C Programming Language' by Brain W. Kernighan. While reading the book, I came across a code that isn't working quite as expected.

The Issue: The console keeps waiting for more input even after I've entered the text I want. Basically there's no way for the console to know when to start processing the input. It'll be really helpful if someone could suggest modifications to the code so that there's a way for the user to instruct the compiler to start processing the input that has been provided.

Code:

#include <stdio.h>

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

    // program to count number of lines, words and characters in input

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

    state = OUT;
    nl = nw = nc = 0;
    while ((c = getchar()) != EOF)
    {
        ++nc;

        if (c == '\n')
            ++nl;
        if (c == ' '  || c == '\n' || c == '\t')
            state = OUT;
        else if (state == OUT)
        {
            state = IN;
            ++nw;
        }
    }

    printf("%d    %d    %d\n", nl, nw, nc);

}

Additional Information:
Book: The C Programming Language - by Brian W. Kernighan
Chapter: A Tutorial Introduction (Page 20)
Using Xcode Version 8.3.3 (8E3004b)

Upvotes: 1

Views: 72

Answers (1)

cleblanc
cleblanc

Reputation: 3688

On a Unix-like system, if you type CTRL-D at the start of a line in the console, that's equivalent to EOF (the condition in your while loop). If you're on Windows, use CTRL-Z instead.

Upvotes: 2

Related Questions