2

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")

M. Rostami
  • 999
  • 3
  • 16
  • 27
mohammad ghari
  • 153
  • 2
  • 13

3 Answers3

4

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.

Chun Liu
  • 903
  • 5
  • 11
3

No need for 'e'. Replace it with an underscore and remove the print statement.


import (
    "fmt"
    "os"
)
func main() {
    fmt.Print("Enter text: \n")
    var input string
    _, err := fmt.Scanln(&input)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    fmt.Println(input)
}
VC Healy
  • 84
  • 9
0

For the record. If you want to input a numeric value, fmt.Scan stores the value in a variable as a string, if you would like perform any mathematical operation with it, you need to convert it either to int or float. A quick example:

func main() {
    fmt.Println("Type your age: ")

    var input string
    _, err := fmt.Scanln(&input)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    fmt.Printf("%T\n", input)        // outputs string
    inputInt,_ := strconv.Atoi(input)   
    fmt.Printf("%T\n", inputInt)     // outputs int
    fmt.Printf("You were born in %d\n", 2021-inputInt)
}

Took me a while to figure it out, hope it helps!