0

I've been trying to learn some C language via "The C Programming Language by BRIAN W KERNIGHAN & DENNIS M. RITCHIE", and I've got a question that I cannot understand.

Here's the deal, in section 1.5 (page 17) related to character counting of an input, here's my code:

#include <stdio.h>

int main()
{
    double nc;

    for (nc = 0; getchar() != EOF; ++nc);
    printf("%0.f\n", nc);
}

This part:

printf("%0.f\n", nc);

Should print the actual character counter, right? The problem is that it gives me exactly nothing. I've been trying it via Code Blocks and also via terminal by doing "cc code.c", and all it does it just waits for me to put and input, and just nothing more.

Am I missing something here?

Thanks in advance,

Anoubis

V. Anoubis
  • 11
  • 2
  • I just put random characters. Texts, single characters, single integer, nothing works for me. I am clearly doing something wrong – V. Anoubis Mar 04 '16 at 06:54
  • Are you sure the format was not `%.0f`, requesting 0 digits after the decimal point? Also, running `cc code.c` will create a program `a.out`, and you would need to run that: `./a.out < code.c` for example, to make it count its own source code. – Jonathan Leffler Mar 04 '16 at 06:57
  • The code is working fine taking a string from stdin - it must be the way you do the input that is wrong – Support Ukraine Mar 04 '16 at 06:58
  • Please note that through that book you are only the 1989 version of the C language. You might want to consider learning the 2011 version instead - why would you want to learn 27 years old technology and an obsolete standard? – Lundin Mar 04 '16 at 07:43
  • @Lundin I didn't even know there was a 2011 version of this book. Unless, you're talking about other book... – V. Anoubis Mar 11 '16 at 09:05
  • @V.Anoubis I meant, learn the 2011 version of the _language_. Regarding the K&R book, there is no hope for it to get fixed. At the very least you need to find the erratas, there's a couple of pages that list the most blatant errors. – Lundin Mar 11 '16 at 09:09

2 Answers2

2

You are trapped here getchar() != EOF if you only input random text input.

The program wait for EOF - End Of File

I copied your code into a.cand compiled it using gcc a.c -o a.out

If a run ./a.out I get the behaviour you describe until I hit Ctrl+D which corresponds to EOF in my terminal.

The program will print the number of chars received once it has received EOF.

Another way to use the code is to pipe another file to it.

Create a dummy file named blaha.txtand write something in it. You can then pipe it to the program like this: a.out < blaha.txt

Emil
  • 456
  • 4
  • 9
1

Your program waits for input and consumes it until it reaches the end of file. You can signal the end of file from the terminal by typing a special character such as control-Z followed by enter on Windows and control-D on linux and MacOS.

chqrlie
  • 131,814
  • 10
  • 121
  • 189