Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an input from keyboard without 'return' in C

Tags:

c

macos

How do i get an input from keyboard, without pressing 'return' in C / Mac Os

like image 842
cGio Avatar asked Mar 30 '10 20:03

cGio


People also ask

How do you get a character without pressing Enter in C?

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.

What is getch () in C language?

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.

Which function accepts input without displaying it on screen?

scanf() without displaying on screen.

Does Getchar wait for input?

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 .


2 Answers

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.

like image 70
Thomas Pornin Avatar answered Oct 14 '22 04:10

Thomas Pornin


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?

like image 27
jamesdlin Avatar answered Oct 14 '22 06:10

jamesdlin