Echoing Characters with getchar() in a Loop

  • Thread starter Thread starter keltix
  • Start date Start date
  • Tags Tags
    Loop
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
8 replies · 3K views
keltix
Messages
42
Reaction score
0
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?
 
Physics news on Phys.org
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:
fflush(stdout);
After putch.
 
that just reads without echoing (i.e. w/o printing strokes on screen)
 
Coin, the fflush didn't work.

good guess though
 
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.
 
system-specific API?

idk what that is, but yea it only works after pressing enter
 
keltix said:
system-specific API?
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 let's you make windows and stuff should have ways to get keypresses.