Home > Back-end >  Go | request data from the keyboard
Go | request data from the keyboard

Time:09-17

I can't find how to request data from the keyboard on GO.

Or rather, I found it. But what I found did not work fully. Here is the code:

fmt.Println("input : ")
var command string
fmt.Scanln(&command)

The bottom line is that I have to get the whole line and for some reason a space separates the request.

Also removes the letter of the next word?

Python has such a cool thing called input.

CodePudding user response:

Use a bufio.Scanner on os.Stdin:

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)

    readLine := func() (ln string, ok bool) {
        for {
            fmt.Print("? ")
            if ok = scanner.Scan(); !ok {
                break
            }
            if ln = scanner.Text(); ln != "" {
                break
            }
            fmt.Println("You didn't enter any text.")
        }
        return ln, ok
    }

    fmt.Println("Please enter some text at the prompt. Type 'exit' to quit.")
    for ln, ok := readLine(); ok; ln, ok = readLine() {
        fmt.Printf("You entered: %q\n", ln)
        if ln == "exit" {
            break
        }
    }

    if err := scanner.Err(); err != nil {
        panic(err)
    }

    fmt.Println("Goodbye!")

}
  • Related