fmt.Scanln outputs all expect the first character to the terminal


In the following code, if the user inputs a string. All expect the first character is input back to the terminal by the program. Any help in understanding this abnormality is appreciated. Thank you.

Go version 1.15

package main

import "fmt"

func main() {
    a := 0

Hi @gokulpm,

Variable a is an integer and cannot hold a string. fmt.Scanln() reads the first character of the input, decides that this is not a number, and stops further reading.
The program then prints the value of a (which is still 0) and exits.

The shell now takes over the remaining input as a new command, fails to find a command by that name, and complains.

Tip: never ignore the errors that a function returns. fmt.Scanln() has two return values: the number of successfully read characters, and an error value. (Type go doc fmt.Scanlnin the shell for info aboutScanln`.)

Try n, err := fmt.Scanln(&a) and print out the error if it is nil. This way you can quickly see what went wrong.


Thank you for the explanation. Cheers.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.