Thread: getchar() and other library functions

  1. #1
    back? dbaryl's Avatar
    Join Date
    Oct 2001
    Posts
    597

    getchar() and other library functions

    OK, I was just looking in the book and saw this: int getchar(void); in stdio.h.... now, doesn't getchar(); return a char, not an int?

    Where can I find the general description for most library functions like this?

    [edit]'tupid spelling errors =)
    This is my signature. Remind me to change it.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Location
    Fiji
    Posts
    212
    getchar() returns an int, the int's value is the ASCII character number.

    char c;
    c = (char) getchar();

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No. It returns an int. Actually all of the 'char' related functions, such as 'fgetc', 'fputc', getchar, etc, all take and return integers rather than characters.

    The reason they do this is so you can test them for non-char values, such as EOF.

    One of the best books I've found is the "Microsoft C Bible", an older book, but it has supurb examples and information on every function.

    This is part of the reason I like their MSDN so much. (I prefer the disk-based MSDN myself, but the online version is still nice.)

    Other than that, there are many resources (available at your favourite search engine); Here is one such resource.

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    back? dbaryl's Avatar
    Join Date
    Oct 2001
    Posts
    597
    Originally posted by kwigibo
    char c;
    c = (char) getchar(); [/B]
    Is this casting necessary, or is
    Code:
    c = getchar();
    good enough? I'd assume the conversion would be done automatically. Also, is there a function that returns the ascii value for a char?
    This is my signature. Remind me to change it.

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by dbaryl
    Is this casting necessary, or is
    Code:
    c = getchar();
    good enough? I'd assume the conversion would be done automatically. Also, is there a function that returns the ascii value for a char?
    Yes, the conversion is done automatically, but you'll loose significant bits. As already stated, the return is an int. It is so, because EOF is an int, normally with the value -1. This value is outside the range of a char, so by assigning the return to a char, you loose the ability to test for EOF.

    Therefore, the code should be:
    Code:
    int c;
    c = getchar();
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed