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 : Generate MD5 checksum of a file
+4.1k Golang : Check if user agent is a robot or crawler example
+2.6k Golang : How to calculate the distance between two coordinates using Haversine formula
+3.8k Golang : Another camera capture GUI application with GTK and OpenCV
+2k Mac OSX : Get disk partitions' size, type and name
+8.7k Golang : Get IP addresses of a domain name
+1.4k Javascript : Change page title to get viewer attention
+3.6k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+2.6k Javascript : How to replace HTML inside <div>?
+2k Golang : Calculate half life decay example
+15.4k Golang : Get current file path of a file or executable
+17.8k Golang : Upload to S3 with official aws-sdk-go package