Echoing Characters with getchar() in a Loop

  • Thread starter Thread starter keltix
  • Start date Start date
  • Tags Tags
    Loop
AI Thread Summary
Using getchar() in a loop captures characters but may not print them immediately due to output buffering in C. By default, stdout buffers output for efficiency, causing all captured characters to be printed at once after pressing enter. To echo each character immediately, flushing stdout with fflush(stdout) after each putch call is recommended. However, this may not resolve the issue if the program only receives input after the enter key is pressed. For capturing individual keystrokes without waiting for enter, system-specific APIs like _getch() on Windows or similar functions in the curses library for UNIX systems can be utilized. These APIs allow for real-time keypress detection without the need for additional input confirmation.
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?
 
Technology news on Phys.org
Try _getch() instead.
 
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.
 

Similar threads

Back
Top