小编典典

reader.ReadString不会去除首次出现的delim

go

我写了一个简单的go程序,它不能正常运行:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Who are you? \n Enter your name: ")
    text, _ := reader.ReadString('\n')
    if aliceOrBob(text) {
        fmt.Printf("Hello, ", text)
    } else {
        fmt.Printf("You're not allowed in here! Get OUT!!")
    } 
}

func aliceOrBob(text string) bool {
    if text == "Alice" {
        return true
    } else if text == "Bob" {
        return true
    } else {
        return false
    }
}

它应该要求用户说出它的名字,如果他是爱丽丝还是鲍勃,则向他打招呼,否则告诉他离开。问题是,即使输入的名称是Alice或Bob,它也会告诉用户离开。

爱丽丝:

/usr/lib/golang/bin/go run /home/jcgruenhage/go/workspace/src/github.com/jcgruenhage/helloworld/greet/greet.go
Who are you? 
Enter your name: Alice
You're not allowed in here! Get OUT!!
Process finished with exit code 0

鲍勃:

/usr/lib/golang/bin/go run /home/jcgruenhage/go/workspace/src/github.com/jcgruenhage/helloworld/greet/greet.go
Who are you? 
Enter your name: Bob
You're not allowed in here! Get OUT!!
Process finished with exit code 0

阅读 462

收藏
2020-07-02

共1个答案

小编典典

这是因为您text正在存储Bob\n

解决此问题的一种方法是使用strings.TrimSpace修剪换行符,例如:

import (
    ....
    "strings"
    ....
)

...
if aliceOrBob(strings.TrimSpace(text)) {
...

另外,您也可以使用ReadLine代替ReadString,例如:

...
text, _, _ := reader.ReadLine()
if aliceOrBob(string(text)) {
...

之所以string(text)需要,是因为ReadLine将返回您byte[]而不是string

2020-07-02