Thread: getchar EOF confusion

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    2

    getchar EOF confusion

    Hello,

    I have following program that I got from the C book

    Code:
    #include <stdio.h>
    main()
    {
    long nc;
    nc = 0;
    while (getchar() != EOF)
    ++nc;
    printf("%ld \n",nc);
    }
    The program is in a loop as you can see. But not sure how to enter the EOF character using my keyboard to terminate the prgram.

    What is the actual character value of EOF. I know that integer value is -1.

  2. #2
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    ctrl+D might work, but I suggest you to use some other method for terminating the input

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by webofunni View Post
    Hello,

    I have following program that I got from the C book


    The program is in a loop as you can see. But not sure how to enter the EOF character using my keyboard to terminate the prgram.

    What is the actual character value of EOF. I know that integer value is -1.
    EOF is not character entered (character values are 0-255) - it is return value indicating read error or end of stream event

    to emulate it from terminal - press Ctrl+D on linux or Ctrl+Z on Windows.

    Another way - just redirect stdio to read from file like:

    myprogram <myinput.txt

    in this case the contents of the file will be sent to the myprogram stdio by the shell, when the whole file will be read getchar will return EOF
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by webofunni View Post
    Hello,

    What is the actual character value of EOF. I know that integer value is -1.
    EOF is a macro which indicates the end of input.its value is -1 but it can be any of the negative integer.in windows press ctrl+z to terminate.
    you can also use '\n' character to terminate your program.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getchar terminating with new line or EOF
    By rocksteady in forum C Programming
    Replies: 1
    Last Post: 10-19-2007, 01:19 PM
  2. Getchar(), Keyboards, and EOF?
    By Epo in forum C Programming
    Replies: 5
    Last Post: 10-13-2004, 06:21 PM
  3. Replies: 2
    Last Post: 11-10-2003, 09:12 PM
  4. questions about getchar() and EOF
    By kermit in forum C Programming
    Replies: 4
    Last Post: 02-04-2003, 05:14 PM
  5. Can anybody take a look at this?
    By TerryBogard in forum C Programming
    Replies: 10
    Last Post: 11-21-2002, 01:11 PM