How do i get an input from keyboard, without pressing 'return' in C / Mac Os
Using standard C/C++, you cannot. However, if you're lucky your compiler may have the non-standard conio. h header (which might include getch() ), if you're on *nix (UNIX, Linux, etc.) you can try the ncurses library or switching the terminal mode.
getch() method pauses the Output Console until a key is pressed. It does not use any buffer to store the input character. The entered character is immediately returned without waiting for the enter key. The entered character does not show up on the console.
scanf() without displaying on screen.
Returns the character read. These functions wait for input and don't return until input is available. To indicate a read error or end-of-file condition, getchar returns EOF , and getwchar returns WEOF .
On Unix-like systems with terminals (I suppose that MacOS X qualifies), then you need to set the terminal to so-called "cbreak" mode. The point is that the terminal is keeping the data until "return" is pressed, so that there is nothing your C code can do, unless it instructs the terminal not to do such buffering. This is often called "cbreak mode" and involves the tcsetattr()
function.
A bit of googling found this code which seems fine. Once the terminal is in cbreak mode, you will be able to read data as it comes with standard getchar()
or fgetc()
calls.
From the comp.lang.c FAQ: How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With