Get Single Char from Console Immediately

Get single char from console immediately

Yes, there are numerous ways to do this, and besides gems you can directly manipulate with terminfo through gems for termios, ncurses or stty program.

tty_param = `stty -g`
system 'stty raw'

a = IO.read '/dev/stdin', 1

system "stty #{tty_param}"

print a

How to get a single character without pressing enter?

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999

#!/usr/bin/ruby

begin
system("stty raw -echo")
str = STDIN.getc
ensure
system("stty -raw echo")
end
p str.chr

(Tested on my OS X system, may not be portable to all Ruby platforms). See http://www.rubyquiz.com/quiz5.html for some additional suggestions, including for Windows.

How to read a single char from the console in Java (as the user types it)?

What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.

Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:

If your program must be console based,
you have to switch your terminal out
of line mode into character mode, and
remember to restore it before your
program quits. There is no portable
way to do this across operating
systems.

One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.

Reading a single character in C

scanf("%c",&in);

leaves a newline which is consumed in the next iteration.

Change it to:

scanf(" %c",&in); // Notice the whitespace in the format string

which tells scanf to ignore whitespaces.

OR

scanf(" %c",&in);
getchar(); // To consume the newline

How to read a single character from the user?

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()

Reading a single char in Java

You can either scan an entire line:

Scanner s = new Scanner(System.in);
String str = s.nextLine();

Or you can read a single char, given you know what encoding you're dealing with:

char c = (char) System.in.read();

Is there a way to accept a single character as an input?

You can use System.in.read() instead of Scanner

char input = (char) System.in.read();

You can also use Scanner, doing something like:

Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);

For using Stringinstead of char, you can also to convert to String:

Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));

This is less fancy than other ways, but for a newbie, it'll be easier to understand. On the other hand, I think the problem proposed doesn't need amazing performance.

Capture characters from standard input without waiting for enter to be pressed

That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin (they are usually line buffered). You can, however use a library for that:

  1. conio available with Windows compilers. Use the _getch() function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <conio.h> and use it. See conio.h at Wikipedia. It lists getch(), which is declared deprecated in Visual C++.

  2. curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch() function. (try man getch to view its manpage). See Curses at Wikipedia.

I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty). Curses would handle that for you in a portable manner, if I'm not mistaken.



Related Topics



Leave a reply



Submit