gogofmt

how can I take input from user in Golang (fmt.scan)


I can not take input from the user in Golang by use fmt.scan().

package main

import "fmt"

func main() {
    fmt.Print("Enter text: ")
    var input string
    e, _ := fmt.Scanln(&input)
    fmt.Println(input)
    fmt.Println(e)
}

image of code

After stopping the debugger: image of code The err added to code, but nothing happened.

func main() {
    fmt.Print("Enter text: ")
    var input string
    e, err := fmt.Scanln(&input)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    fmt.Println(input)
    fmt.Println(e)
}

Image after add err in my Code. What is "not available" in Next line (after my Input value: "51213")


Solution

  • You code has no problem. If you build your code with go build and run the binary directly in a terminal, you will see your code runs.

    The problem you hit is because of the Delve and vscode debug console. The vscode debug console doesn't support read from stdin. You can check this issue: Cannot debug programs which read from STDIN for details.