Guest123ABC
Guest123ABC

Reputation: 23

K&R's C Program pg. 17 Line Counting Program results always 0

I have been reading K&R's The C Programming Language. When I typed in the example program on page 17 to count lines, the program always results are always 0. Here is my code:

/* Taken from The C Programming Language by Brian W. Kernighan and 
 * Dennis M. Ritchie */

/* Include statement added for compatibility */
#include "stdio.h"

main()    /* count lines in input */
{
  int c, nl;

  nl = 0;
  /* EOF in Linux is ctrl-D and ctrl-Z on Windows */
  while ((getchar()) != EOF)
    if (c == '\n')
      ++nl;
  printf("%d\n", nl);
}

Upvotes: 0

Views: 93

Answers (1)

John Zwinck
John Zwinck

Reputation: 249093

while ((getchar()) != EOF)

should be

while ((c = getchar()) != EOF)

Does your copy of the book really get that wrong? I checked mine, which is the Second Edition, and it has the program on page 19 rather than your 17, and the code is correct.

Something that will pay huge dividends for you as you begin to program in C is to always enable all available compiler diagnostics. In this case, gcc -Wall -Wextra -Werror refuses to compile this program, saying:

error: ‘c’ may be used uninitialized in this function [-Werror=uninitialized]

Upvotes: 4

Related Questions