1

I'm a middle experienced Java developer and have many problems learning the C language for my computer science study. I try it with the book "The C Programming Language" which many people seem to recommend.

But I've got problems with the simplest stuff like the EOF in combination with getchar(). Here's the code:

#include<stdio.h>
main()
{
    int i = 0;
    while (getchar() != EOF)
    {
        ++i;
        printf("Count of characters is %d", i);
    }
}

I'm working with Mac OS X Lion and use the "cc" command with "./a.out" for running in terminal, like described in the book to run the file. And what I get is:

  • Always counting one character too much
  • the while loop never ends! it just waits for another input after reaching end of input ...

I really have no idea what could be the issue. Can someone help?

CGee
  • 1,650
  • 5
  • 20
  • 31
  • 1
    Try running the program with a file as input (not a terminal) by redirecting stdin. And learn how to use a debugger. Always compile with warnings enabled, e.g. `gcc -Wall -g yourprog.c -o yourbin` – Basile Starynkevitch Nov 29 '11 at 17:49
  • 1
    On Linux to end the input from the terminal, you've to type CTRL+d, on Windows CTRL+z, on Mac I don't know, but I suppose it could be like Linux, being Unix based. – stivlo Nov 29 '11 at 17:52
  • How did you declare and initialize `i`? Like basile said, redirect stdin. And you'll want to add `\n` to the end of that string. – Kevin Nov 29 '11 at 17:53
  • Redirect stdin? Sorry but I'm really new to this and don't know what you mean. The same is true for the compiler properties: why are you using gcc and not cc like in the book? What's the difference? And where's the bin file? Is it the a.out? – CGee Nov 29 '11 at 17:54
  • On OS X, `cc` is `gcc`. When the book was written (depending on edition?), gcc didn't exist. – Wooble Nov 29 '11 at 18:39

2 Answers2

4

Always counting one character too much

That could be the newline (enter / return).

the while loop never ends! it just waits for another input after reaching end of input

You are likely not signaling end of input. You should be using CTRL-D to do so.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Thank you, got it! So the the terminal end is not with a return but with a CTRL-D? Then all would make sense ... – CGee Nov 29 '11 at 17:56
  • @user1035741 On Unix it's `Ctrl-D`. On DOS it's `Ctrl-Z`. Piping the input (`echo "This is the end" | ./a.out` or `./a.out < file`) will also send work. – cnicutar Nov 29 '11 at 17:58
0

When you type a character, such as "6" and you click enter (which is equal to \n), then the command "6\n" is sent, so it is 2 characters. If you just press enter, then 'i' will be increased by 1.

The EOF means end of file and its equivalent to ctrld+D. It is useful if you read a text file. Else it is the same as saying "Forever".

gsach
  • 5,715
  • 7
  • 27
  • 42