0

so I built a very basic program according to The C Programming Language book, but when I run it, it keeps asking input after I enter one, the loop should ended when there are no inputs longer right? or Am I wrong? srry for my bad english

int main()
{
    long nc;
    nc = 0;

    while ( getchar() != EOF) {
    ++nc;
    }
    printf("%ld\n", nc);
}

4 Answers4

2

Your loop is expecting an EOF character to terminate, not just an empty string. *nix consoles typically translate a Ctrl-D on an empty line as EOF, in Windows I believe it's Ctrl-Z but I could be wrong.

tzaman
  • 46,925
  • 11
  • 90
  • 115
  • By the way, *EOF* stands for *end of file*. You are terminating the standard input stream when you enter the EOF character. – D.Shawley Mar 07 '14 at 01:00
  • end-of-file is a condition, not a character ... note that getchar() returns int, not char, specifically because `EOF` doesn't fit in a char. On POSIX systems, getchar() returns EOF when the read() system call returns 0. For a file, that's when the end of the file is reached. For a terminal, that's when ctrl-D is entered immediately after a newline or another ctrl-D (that's right, ctrl-D in the middle of a line does not produce EOF -- try it if you don't believe it). – Jim Balter Mar 07 '14 at 01:10
  • 1 more questions... why the EOF stroke must be pressed after a new line, it's not working when pressed after my input ex: test^Z – Abirafdi Raditya Putra Mar 07 '14 at 01:35
1

No.

For standard input, you must input EOF manually. It's Ctrl+Z in Windows and Ctrl+D in Linux.

If you are using Linux and redirect standard input from file. It will end.

Bin Wang
  • 2,697
  • 2
  • 24
  • 34
0

This will keep reading input until it gets to an end-of-file. If you're reading from the terminal (you haven't redirected the program to read from a file), it will only get an EOF if you explicitly give it one. How you do that dpends on your OS, but on most UNIX-like systems, you can generate an explicit eof by hitting ctrl-D

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
0

You can press the Ctrl + D to input EOF, anything other keyboard can't! So if you want to interrupt the loop, you must input the EOF.

Chandrayya G K
  • 8,719
  • 5
  • 40
  • 68