Problem with getch() and fgetc()

This is a discussion on Problem with getch() and fgetc() within the C Programming forums, part of the General Programming Boards category; I have this code, Code: #include <stdio.h> #include <conio.h> int main(void) { char test; test = getch(); printf("CHAR: %d\n", test); ...

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    14

    Problem with getch() and fgetc()

    I have this code,
    Code:
    #include <stdio.h>
    #include <conio.h>
    
    int main(void)
    {
        char test;
        test = getch();    
        printf("CHAR: %d\n", test);
    
        test = fgetc(stdin);
        printf("CHAR: %d", test);
    
        return 0;
    }
    When i press ENTER key on both input prompt,
    getch() returns 13, while fgetc() returns 10,
    can anyone tell me why?

    Aren't they supposed to do the same thing (get one character from user) ?

    Thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Because '\n' is 10, and '\r' is 13. They're used in pairs.

    Furthermore, 'test' should be an int, not a char.

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

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    14
    Thanks for your reply.

    So ENTER key can be either '\n' or '\r' ?

    If so, how do i know when pressing ENTER key will returns '\n' or '\r' ?


    Thanks.

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    No, what quzah said was in pairs. So that when you press enter, both keys are generated (I believe this is Microsoft's dinosaur).

    With buffered io, getch will retrieve the first key (say 'q', for instance), but wait for the enter key as a "courtesy". However, if there are more calls to getch immediately downstream, they will probably recieve the enter key(s) and thus royally throw things off! Unbufferd io doesn't wait afterward but the after-effect is the same.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21