[go-nuts] getchar()

1,562 views
Skip to first unread message

Anschel

unread,
May 8, 2010, 11:11:47 PM5/8/10
to golang-nuts
I'm sure this is totally obvious, but I can't seem to find it anywhere
in the docs. Is there a go equivalent of getchar() in C? Actually come
to think of it it's not at all obvious how to do even normal io...am I
missing something?

Thanks,
--Anschel

Steven

unread,
May 9, 2010, 12:14:31 AM5/9/10
to Anschel, golang-nuts
Yes, you're missing the package documentation:

Package os has the Files os.Stdin, os.Stdout, and os.Stderr open. Package bufio gives you buffered access. Example usage:

reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')

You might also want to look at package scanner (not go/scanner). It allows slightly more convenient access, if you want to get things like integers. For output, there's package fmt. It should have some familiar functions.

Anschel

unread,
May 9, 2010, 1:48:44 AM5/9/10
to golang-nuts
> reader := bufio.NewReader(os.Stdin)
> input, _ := reader.ReadString('\n')

This is fine for reading a line, but how do I read just one character
or byte without waiting for the user to hit Return?
reader.ReadByte() still waits for a newline before returning control
to the program.

I think what I want to do is set the terminal to raw mode, but I don't
really see how to do that.

peterGo

unread,
May 9, 2010, 4:55:22 AM5/9/10
to golang-nuts
Anschel,

One way to get answers to questions is to search the golang-nuts
mailing list to see if the question has already been answered. For
example,

How to obtain raw character input?
http://groups.google.com/group/golang-nuts/browse_thread/thread/89c31f605f302429/d485483dfe8a8ca4

Peter

⚖ Alexander "Surma" Surma

unread,
May 9, 2010, 5:28:47 AM5/9/10
to Anschel, golang-nuts
You do realize, that even C's getchar() requires the user to hit enter?
There is ncurses' getch(), where you actually wait for a single
keystroke. So you have to options: Look around for ncurses bindings
(github et al. I'm sure somebody bothered) or you manually open
/dev/tty.

Surma
Reply all
Reply to author
Forward
0 new messages