Question:

In C, how does getchar actually work?

by  |  earlier

0 LIKES UnLike

When using getchar to read a character from the user:

asc = getchar();

It would seem that this would only read one character, however, in this case it reads until ENTER is pressed! And as far as I understand it, C stores the input somewhere and allocates it ordinarily later if more "getchars" are used.

For example: if the user inputs "Hello", then asc would get H's ASCII value, BUT, C will remeber the characters "ello" and allocate them later or something.

Could anyone please explain what's the thing with this command?

Thank you.

 Tags:

   Report

3 ANSWERS


  1. getchar() simply reads the next character from stdin.  If stdin is buffered at the O/S level, the only thing you can do is tell the O/S not to buffer it.  How this is done depends on the O/S.

    Under Windows, you have _getch() and _getche() to get (without, and with echo, respectively) a single character from the keyboard.  Note, however, that you can't mix _getch/_getche with the standard stdin routines.

    Under Unix/Linux, you would have to use ioctl() to change the mode of stdin to "raw" to turn it unbuffered.  An alternative would be to use a package like curses to handle all the I/O.

    - kb -

    P.S.  Note that "fflush(stdin)" is undefined according to the C standard.  Your particular compiler may give meaning to the construct.


  2. Essentially stdin takes everything from the keyboard and and stores it in  buffer which releases it when enter is hit.  If you just want to get the characters as they are hit, you have to bypass the buffer and go with a lower level library such as Ncurses or conio.h.  So if you want to getchar several characters, call getchar and allocate them, prompt the user for enter and do an fflush(stdin) once you've got the enter char.

  3. getchar gets the next character from stdin until eof or error.

    How stdin input is stored is actually up to the operating system.

    It is a pain waiting for ENTER (eof) to be pressed.  That's why C++ line functions tend to be easier to use.

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.