Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()
). I know there's a function in Windows for it, but I'd like something that is cross-platform.
getchar() to read one character from keyboard We can use getchar function to read a single character from the keyboard. We will try to take one sample character and display by using printf function. Once the program encounters the getchar() function it will wait for the user to enter data by keyboard.
During the program execution, a single character is get or read through the getchar(). The given value is displayed on the screen and the compiler wait for another character to be typed. If you press the enter key/any other characters and then only the given character is printed through the printf function.
To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character.
The getchar() function reads a single character from the standard input device( keyboard).
Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:
getch()-like unbuffered character reading from stdin on both Windows and Unix
class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch()
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