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
+13.2k Golang : Get uploaded file name or access uploaded files
+5.9k Golang : Check if password length meet the requirement
+11.3k Golang : Encrypt and decrypt data with x509 crypto
+16k Golang : Get input from keyboard
+11.5k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+9.6k Golang : Allow Cross-Origin Resource Sharing request
+10.1k Nginx : TLS 1.2 support
+4k Python : Find out the variable type and determine the type with simple test
+11.4k Android Studio : Highlight ImageButton when pressed on example
+13.5k Golang : Overwrite previous output with count down timer
+11k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+9.2k Golang : Channels and buffered channels examples