I wrote a simple go program and it isn\'t working as it should:
package main
import (
\"bufio\"
\"fmt\"
\"os\"
)
func main() {
reader := bu
reader.ReadLine()
Can leave ‘\n’ but reader.ReadString() can't
This is because your the text is storing Bob\n
One way to solve this is using strings.TrimSpace to trim the newline, eg:
import (
....
"strings"
....
)
...
if aliceOrBob(strings.TrimSpace(text)) {
...
Alternatively, you can also use ReadLine instead of ReadString, eg:
...
text, _, _ := reader.ReadLine()
if aliceOrBob(string(text)) {
...
The reason why the string(text) is needed is because ReadLine will return you byte[] instead of string.
I think the source of confusion here is that:
text, _ := reader.ReadString('\n')
Does not strip out the \n, but instead keeps it as last value, and ignores everything after it.
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.
https://golang.org/src/bufio/bufio.go?s=11657:11721#L435
And then you end up comparing Alice and Alice\n. So the solution is to either use Alice\n in your aliceOrBob function, or read the input differently, as pointed out by @ch33hau.
I don't know anything about Go, but you might want to strip the string of leading or trailing spaces and other whitespace (tabs, newline, etc) characters.