0

Possible Duplicate:
EndOfFile in C - EOF

I was trying examples from K&R. I am not able to understand why this code does not exit unless ctrl+c is pressed.

int main ( )
{
    int c; 
    c = getchar(); 
    while(c!=EOF)
        {
            putchar(c);   
            c=getchar();
        }
}

Any help is appreciated. Thanks!

EDIT: Using Windows (Visual Studio 2010)

Community
  • 1
  • 1
Shash
  • 4,160
  • 8
  • 43
  • 67
  • on which system are you trying this ? Windows ? Unix ? Linux ? How do you input EOF ? (usually Ctrl+D on linux boxes) – BigMike Sep 17 '12 at 12:05

3 Answers3

8

In Windows, you generate end of file from the standard input stream by pressing Ctrl+Z. Depending on the buffering behavior, you might also need to press Return.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • +1 concise, neat and correct. – BigMike Sep 17 '12 at 12:07
  • @BigMike Thanks, not correct enough to be accepted though, failed to read the original poster's mind. :) – unwind Sep 17 '12 at 12:35
  • OP asked how to trap EOF, not \n, thus this is the correct answer IMHO. If that program is used in a pipe, changing the test on EOF to a test on \n will simply break it. – BigMike Sep 17 '12 at 14:34
5

EOF is End of File. If you read from 'keyboard', you should compare to End of Line symbol which is equal to press Return

int main ( )
{
    int c; 
    c = getchar(); 
    while(c!= '\n')
    {
        putchar(c);   
        c=getchar();
    }
}
Blood
  • 4,126
  • 3
  • 27
  • 37
-1
On Windows machine ctrl+c acts as delimiter of character scanning same as EOF 
on this loop gets broken otherwise it will keep looking for characters
Anshul garg
  • 233
  • 2
  • 6