How to read from standard input in the console?

后端 未结 11 1173
迷失自我
迷失自我 2020-11-28 00:54

I would like to read standard input from the command line, but my attempts have ended with the program exiting before I\'m prompted for input. I\'m looking for the equivalen

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 01:38

    Another way to read multiple inputs within a loop which can handle an input with spaces:

    package main
    import (
        "fmt"
        "bufio"
        "os"
    )
    
    func main() {
        scanner := bufio.NewScanner(os.Stdin)
        var text string
        for text != "q" {  // break the loop if text == "q"
            fmt.Print("Enter your text: ")
            scanner.Scan()
            text = scanner.Text()
            if text != "q" {
                fmt.Println("Your text was: ", text)
            }
        }
    }
    

    Output:

    Enter your text: Hello world!
    Your text was:  Hello world!
    Enter your text: Go is awesome!
    Your text was:  Go is awesome!
    Enter your text: q
    

提交回复
热议问题