How to read from standard input in the console?

后端 未结 11 1154
迷失自我
迷失自我 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:29

    Cleanly read in a couple prompted values:

    // Create a single reader which can be called multiple times
    reader := bufio.NewReader(os.Stdin)
    // Prompt and read
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Print("Enter More text: ")
    text2, _ := reader.ReadString('\n')
    // Trim whitespace and print
    fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
        strings.TrimSpace(text), strings.TrimSpace(text2))
    

    Here's a run:

    Enter text: Jim
    Enter More text: Susie
    Text1: "Jim", Text2: "Susie"
    

提交回复
热议问题