-3

This is a program from the book "C The Programming Language".

it is supposed to take an input and count the number of lines.

#include <stdio.h>

int main(void)
{
    long c, nl;

    nl = 0;
    while ((c = getchar()) != EOF)
        if (c == '\n')
            ++nl;
    printf("%d\n", nl);
}

When I run the program and provide an input it keeps adding newline after hitting Enter.

  • 4
    It's looking for EOF, so you have to close stdin. (Ctrl-D, I think). – 001 Jun 07 '23 at 14:47
  • 1
    What do you expect it to do? – Andrew Henle Jun 07 '23 at 14:47
  • I hope you have at least the ANSI C version of this dusty old tome. – tadman Jun 07 '23 at 14:48
  • 2
    You'll need to end input, like CTRL+D or CTRL+Z depending on your OS. – tadman Jun 07 '23 at 14:49
  • 1
    You need to press ctrl+d on Linux/Mac or ctrl+z on an empty line in Windows to generate EOF and break the loop. – Retired Ninja Jun 07 '23 at 14:49
  • @tadman I don't even know what the ANSI is ? but, your solution is right Thank You! – Mahmoud Rehan Jun 07 '23 at 15:04
  • It's an [obsolete C standard](https://en.wikipedia.org/wiki/ANSI_C) a.k.a. C89 as in 1989 as in 34 years ago. There are [other books](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) that might cover newer C standards and have a lot fewer quirks than that book. Remember, that book was intended for compiler developers, not programmers per-se, and does a lot of *extremely* weird things to show off what C can do, not what you, as a programmer, should do. – tadman Jun 07 '23 at 15:05
  • @tadman I have the second edition – Mahmoud Rehan Jun 07 '23 at 15:07
  • @tadman And I have another two books "C Programming absolute Beginners Guide" and "Head First C". – Mahmoud Rehan Jun 07 '23 at 15:11
  • It's great you've got other resources. [This site](https://en.cppreference.com/w/c) offers a really great index of the various C functions available, or you can lean on `man` if your system has such a thing, as in `man strncat`. – tadman Jun 07 '23 at 15:13
  • Unrelated: The proper type for `c` is `int` so there's no need to make it `long`. Also, since you are counting newlines I don't expect that negative values will ever be needed so you could make `nl` `unsigned long` instead. Btw `%d` is not correct for `long`. It should be `%ld` – Ted Lyngmo Jun 07 '23 at 15:13
  • 1
    @TedLyngmo This code is from the 1980s where hair styles were different, MTV played music videos, and we liked our ints *long*. (K&R had some very strange opinions about what C should look like, didn't they?) – tadman Jun 07 '23 at 15:14
  • 1
    @tadman Ah... back when I had hair :-) – Ted Lyngmo Jun 07 '23 at 15:15

1 Answers1

1

Hitting Enter key will give you a new line ('\n')

EOF is caused by a control + Z in Windows and control + D in Linux

thomas
  • 41
  • 6