Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Getchar() loop

  1. Apr 20, 2009 #1
    If you use getchar() to capture a character and then print it to the stdout in a loop,
    why does it first capture the characters in the list (up to whatever max) and then print them all at once?

    In other words, how would I echo every character one at a time using a getchar() loop?
  2. jcsd
  3. Apr 20, 2009 #2
  4. Apr 20, 2009 #3


    User Avatar
    Homework Helper

    Try _getch() instead.
  5. Apr 20, 2009 #4
    Is _getch() available everywhere?

    What is happening to you I think is that you need to flush stdout. In C if you write to a file buffer (stdout is a kind of file buffer) it will buffer a bunch of writes and then write them all at once, for efficiency. "Flushing" forces the write-everything-buffered-at-once operation to happen earlier.

    Try putting:
    After putch.
  6. Apr 20, 2009 #5
    that just reads without echoing (i.e. w/o printing strokes on screen)
  7. Apr 20, 2009 #6
    Coin, the fflush didn't work.

    good guess though
  8. Apr 20, 2009 #7


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    On many (most? all?) systems, your program isn't given any of the characters until you press enter. You need to use some system-specific API if you want to trap individual keystrokes.
  9. Apr 20, 2009 #8
    system-specific API?

    idk what that is, but yea it only works after pressing enter
  10. Apr 20, 2009 #9


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Yah. Things like the _getch() function in the Windows API Jeff mentioned. I believe the curses library (*NIX systems) has a similar function.

    And, of course, any API that lets you make windows and stuff should have ways to get keypresses.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook