3

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

4
  • 1
    Please edit the question to include the code as text. Commented Mar 16, 2019 at 3:41
  • Check for errors. For example, play.golang.org/p/CU9X2Xro7z- Commented Mar 16, 2019 at 4:47
  • @peterSO thanks, I add err to code but Nothing happened Commented Mar 16, 2019 at 6:07
  • I happen to have this executed on my UNIX terminal and it all worked fine. Would you like to execute it on Powershell using the command go run main.go Commented Mar 16, 2019 at 6:23

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.