[Solved] fmt.Scanf does not consume all the characters through the end of the string


Your fmt.Scanf("%d", &i) call only parses an integer from the input, it does not consume input until the end of line.

If you input 3.ls, then 3 is parsed as the decimal number, and . is consumed and will stop the scanning. Your app ends here, so the rest (ls and the newline) will be executed by your shell.

Use bufio.Scanner to read lines, e.g.:

fmt.Print("input string: ")
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
    return // no input
}
var i int
fmt.Sscanf(scanner.Text(), "%d", &i)
fmt.Println("Entered:", i)

See related: Tell me what’s wrong with this code GOLANG

2

solved fmt.Scanf does not consume all the characters through the end of the string