I am dipping my toe with Go
and have written some code to check if y or n is input:
reader := bufio.NewReader(os.Stdin)
fmt.Print("(y / n): ")
text, _ := reader.ReadString('
')
text = strings.ToLower(text)
if strings.Compare(text, "y") == 0 {
fmt.Println("True")
} else {
fmt.Println("Else")
}
When I run this code & type y
(and press enter) I expect to see True
but I get Else
- can anyone see why?
You most likely want something like:
reader := bufio.NewReader(os.Stdin)
fmt.Print("(y / n): ")
text, _ := reader.ReadString('
')
text = strings.ToLower(text[0:len(text)-1])
if strings.Compare(text, "y") == 0 {
fmt.Println("True")
} else {
fmt.Println("Else")
}
As the comment above says, ReadString()
returns the delimiter as part of the string. So you're getting "y " and comparing to "y" - the result is false. (You might rather use the Trim()
function to remove all whitespace from either side of the input,instead!)
Edit: The Trim()
suggestion should always be preferred over the original suggestion. To do otherwise produces non-portable code, as illustrated in the comments to this answer. The complete revised code:
reader := bufio.NewReader(os.Stdin)
fmt.Print("(y / n): ")
text, _ := reader.ReadString('
')
text = strings.ToLower(strings.Trim(text,"
"))
if strings.Compare(text, "y") == 0 {
fmt.Println("True")
} else {
fmt.Println("Else")
}
As @TimCooper pointed out in a comment, "ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter". That means, as your delimiter is , it will get included in the
text
read, so you need to consider that when making comparisons, or strip it out.
As revealed by the discussion on the other answer, simply stripping is not enough. This is probably because the line ending of user input from
stdin
may be different depending on the operating system. In UNIX it's , in Windows it's
. Here's a more portable solution:
if strings.TrimRight(text, "
") == "y" {
I also changed the use of strings.Compare
to a more direct, simpler comparison with "y"
directly.