问题
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println("Hello",text)
How do I check if the user has entered a null value and where do I put the code? Note - I've already tried checking the length = 0 and = " " but, they don't seem to be working.
Please suggest an alternative way for doing this. Thanks!
回答1:
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)
}
来源:https://stackoverflow.com/questions/43490148/how-do-i-check-if-the-user-has-entered-a-null-value-in-go