Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for command line input in Go

Tags:

go

I want to display a "> ", and then have the program wait for the user to type something into the command line and hit enter (and ultimately store that as a byte slice). In Java I would have done something like:

Scanner scanner = new Scanner(System.in);

System.out.print("> ");
String sentence = scanner.nextLine();

I've tried some things involving os.Args, console.ReadBytes('\n'), and bufio.NewReader(os.Stdin), but I still haven't figured it out. Any suggestions would be greatly appreciated. Thanks.

like image 381
user2802602 Avatar asked Sep 21 '13 19:09

user2802602


1 Answers

Some Go code would have probably been helpful so I could tell you what you did wrong. But here is how you would do this in Go:

package main

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

func main() {
    buf := bufio.NewReader(os.Stdin)
    fmt.Print("> ")
    sentence, err := buf.ReadBytes('\n')
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(string(sentence))
    }
}
like image 166
Stephen Weinberg Avatar answered Oct 12 '22 10:10

Stephen Weinberg