Getchar() loop

  • Thread starter keltix
  • Start date
  • #1
42
0

Main Question or Discussion Point

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?
 

Answers and Replies

  • #3
rcgldr
Homework Helper
8,674
509
Try _getch() instead.
 
  • #4
560
1
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.
 
  • #5
42
0
that just reads without echoing (i.e. w/o printing strokes on screen)
 
  • #6
42
0
Coin, the fflush didn't work.

good guess though
 
  • #7
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
17
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.
 
  • #8
42
0
system-specific API?

idk what that is, but yea it only works after pressing enter
 
  • #9
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
17
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 lets you make windows and stuff should have ways to get keypresses.
 

Related Threads for: Getchar() loop

  • Last Post
Replies
11
Views
58K
Replies
3
Views
7K
Replies
10
Views
3K
Replies
1
Views
2K
  • Last Post
Replies
12
Views
1K
  • Last Post
Replies
1
Views
4K
  • Last Post
Replies
14
Views
2K
  • Last Post
Replies
3
Views
1K
Top