Thread: Regarding flushing input level 2 in the tutorial

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    82

    Regarding flushing input level 2 in the tutorial

    Well, my question is, why do we need ( ch != EOF) ?

    Code:
    
    while(( ch = getchar()) != '\n' ); //understand
    
    //don't understand the need of having != EOF 
    while ((ch = getchar()) != '\n' && ch != EOF); 
    So far the only reason I can think of is if user accidently pressed 'Enter' when he's being prompted to enter 2 inputs.

    != EOF can prevent the flushing ends before the 2nd '\n'

    But, are there anymore reasons to it?


    *ps : I just read in another post saying that "To indicate a read error or end-of-file condition, getc and getchar return EOF"
    so does that means , ch != EOF is just for checking whether ch read in values correctly and it's not what I think ? O_O
    Last edited by xeon321; 11-14-2012 at 11:42 PM.

  2. #2
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    stdin isn't guaranteed to be connected to a keyboard. It could be connected to a file, pipe, network device, or something else entirely. EOF is returned when input cannot be read from stdin (either when there's no more data available, or an error occurs). With that said, you can send a signal with most shells to indicate that there's no more input on the stream (typically Ctrl-D or Ctrl-Z). You should always check for EOF if you wish to write portable programs.

  3. #3
    Registered User
    Join Date
    Jun 2012
    Posts
    82
    oh lol , I see now. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help flushing buffer
    By MSF1981 in forum C Programming
    Replies: 2
    Last Post: 02-15-2009, 07:30 PM
  2. Using low-level keyboard for input
    By hdragon in forum C++ Programming
    Replies: 25
    Last Post: 12-24-2007, 02:13 PM
  3. flushing ....
    By twomers in forum C++ Programming
    Replies: 10
    Last Post: 02-09-2006, 12:29 PM
  4. Flushing the input buffer
    By sand_man in forum C Programming
    Replies: 4
    Last Post: 09-15-2005, 05:23 PM
  5. Flushing the input buffer.
    By civix in forum C++ Programming
    Replies: 6
    Last Post: 08-19-2002, 06:41 PM