Input

265 views
Skip to first unread message

Kreel

unread,
Dec 20, 2009, 6:27:47 PM12/20/09
to golang-nuts
Sorry for the silly question.i'm a complete newbie.
what is the best way to capture a char from standard input
(keyboard) ? And an integer?
thx in advance.

Ostsol

unread,
Dec 20, 2009, 9:15:42 PM12/20/09
to golang-nuts
Read from os.Stdin. For example:

package main

import (
"fmt";
"os"
)

func main () {
bytes := make ([]byte, 20);

os.Stdin.Read (bytes);

fmt.Print (string (bytes))
}

-Ostsol

abiosoft

unread,
Dec 21, 2009, 5:28:44 AM12/21/09
to golang-nuts
package main

import (
"fmt";
"os";
"bufio";
)

func main () {

in := bufio.NewReader(os.Stdin);
//the string value of the input is stored in the variable input
input, err := in.ReadString('\n');
fmt.Println(input); //output the string
if err != nil {
// handle error
}

//in case you need to convert it to integer value. import strconv and
use strconv.Atoi(variable)
}

Hope it is useful

Kreel

unread,
Dec 21, 2009, 1:28:58 PM12/21/09
to golang-nuts
Ok, i'm going to try.
Thx a lot to you both.

yuk...@gmail.com

unread,
Dec 21, 2009, 1:40:50 PM12/21/09
to Kreel, golang-nuts
Alternatively, if you want to read  integers from the standard input, files, etc, you can use the scanner package:

http://code.google.com/p/golang/source/browse/src/pkg/scanner

You can do something like

sc := scanner.NewScanner(os.Stdin)
n := sc.NextInt()
fmt.Print(n)
Reply all
Reply to author
Forward
0 new messages