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
+12.7k Golang : How to convert a number to words
+16.1k Golang : When to use init() function?
+8.4k Golang : Copy map(hash table) example
+40.8k Golang : Get hardware information such as disk, memory and CPU usage
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+8.9k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+11.2k Golang : Listen and Serve on sub domain example
+5.1k AWS S3 : Prevent Hotlinking policy
+4.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+19.8k Golang : Encrypt and decrypt data with TripleDES
+7.5k Golang : Progress bar with ∎ character
+4.1k Python : Convert(cast) bytes to string example