1

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)

Harshit Jindal
  • 621
  • 8
  • 26
  • 6
    Press Ctrl Key + Z (or D in Unix). or Execure like `./your_program < textfile.txt` – BLUEPIXY Jul 20 '17 at 19:38
  • You should really get a newer book. Some of the syntax of C has changed since 1988. – stark Jul 20 '17 at 19:49
  • @stark I'd be glad if you could recommend some other book which covers modern syntax – Harshit Jindal Jul 20 '17 at 19:51
  • 1
    The syntax is mostly the same, and IMO it's a good thing that you start with K&R *and* do the exercises too. LPT: Use many compiler diagnostics(warnings). If you're using gcc, these options are almost always recommended: -Wall -Wextra -std=c99 (or some variant, see doc) – Bjorn A. Jul 20 '17 at 20:00
  • 1
    @HarshitJindal Stack Overflow provides [**The Definitive C Book Guide and List**](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) to help facilitate just this type of learning. – David C. Rankin Jul 21 '17 at 01:14

1 Answers1

2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
cleblanc
  • 3,678
  • 1
  • 13
  • 16
  • I still didn't understand one thing. As soon as I press Ctrl+D (EOF character), the output is printed. That implies the code had already analysed all the input before the EOF character. So basically all the work was already done and as soon as Ctrl+D is pressed, the output was printed on the screen that had already been processed. Is that right? – Harshit Jindal Jul 21 '17 at 09:04