bufio.Reader.ReadString()
returns a string
that also contains the delimeter, in this case the newline character \n
.
If the user does not enter anything just presses the Enter key, the return value of ReadString()
will be "\n"
, so you have to compare the result to "\n"
to check for empty input:
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, err := reader.ReadString('\n')
if err != nil {
panic(err) // Don't forget to check and handle returned errors!
}
if text == "\n" {
fmt.Println("No input!")
} else {
fmt.Println("Hello", text)
}
An even better alternative would be to use strings.TrimSpace()
which removes leading and trailing white space characters (newline included; it isn't a meaningful name if someone inputs 2 spaces and presses Enter, this solution also filters that out). You can compare to the empty string ""
if you called strings.TrimSpace()
prior:
text = strings.TrimSpace(text)
if text == "" {
fmt.Println("No input!")
} else {
fmt.Println("Hello", text)
}