Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
Problem :
Your program accepts user input from console(terminal). It was working fine if the user input is in one word, but not for words(i.e whitespaces in between). What is going on and how to fix it?
Solution :
According Golang's official documentation ( http://golang.org/pkg/fmt/#pkg-overview ). Under the Scanning
section :
Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by one;
Scanf, Fscanf and Sscanf require newlines in the input to match newlines in the format; the other routines treat newlines as spaces.
Chances are...that... your program is accepting user input with fmt.Scanf()
function such as below :
fmt.Print("Please enter your name ... ")
fmt.Scanf("%s", &name)
and fmt.Scanf()
function loves to get stopped by white spaces. To fix this problem, use bufio.NewReader()
and bufio.ReadString()
functions to read from standard input (os.Stdin).
For example :
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
consoleReader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name .... \n")
input, _ := consoleReader.ReadString('\n')
fmt.Println("Your name is : ", input)
}
Sample output :
Enter your name ....
Boo Boo Baa
Your name is : Boo Boo Baa
Hope this tutorial can be useful to you. Happy coding!
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.3k Golang : Shuffle strings array
+8.9k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+5.6k Golang : Error handling methods
+15.8k Golang : Get file permission
+5.3k Python : Print unicode escape characters and string
+11.9k Golang : Pagination with go-paginator configuration example
+29k Golang : missing Git command
+15k Golang : How to get Unix file descriptor for console and file
+5.4k PHP : Convert CSV to JSON with YQL example
+22.9k Golang : Randomly pick an item from a slice/array example
+17.5k Golang : Read data from config file and assign to variables
+16.2k Golang : Execute terminal command to remote machine example