Thread: EOF value and getchar

  1. #1
    Registered User
    Join Date
    Aug 2010
    Location
    Dhaka, Bangladesh
    Posts
    16

    EOF value and getchar

    What does mean EOF has a value of -1?

    I cant understand this program especially the if statement even reading (related programs) from several books-

    Code:
    #include <stdio.h>
    
    main()
    {
     int c;
     c = getchar();                         read a character
     while (c != EOF) {                     while (charater is not end-of-file indicator)
      putchar(c);                           output the character just read
      c = getchar();                        read a character
     }
    }
    Last edited by Sharifhs; 08-12-2010 at 11:02 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    getchar() normally returns a character as an unsigned char converted to int. EOF, being a negative integer, is therefore outside of this normal range of values.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Aug 2010
    Location
    Dhaka, Bangladesh
    Posts
    16
    Quote Originally Posted by laserlight View Post
    getchar() normally returns a character as an unsigned char converted to int. EOF, being a negative integer, is therefore outside of this normal range of values.
    What is an unsigned character? I've read about EOF but can't yet understand well
    Last edited by Sharifhs; 08-12-2010 at 11:09 AM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    unsigned means non-negative, because there is no negative sign to cater to.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed