reader.ReadString 不会删除第一次出现的 delim [英] reader.ReadString does not strip out the first occurrence of delim

查看:19
本文介绍了reader.ReadString 不会删除第一次出现的 delim的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的 go 程序,但它不能正常工作:

I wrote a simple go program and it isn't working as it should:

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Who are you? 
 Enter your name: ")
    text, _ := reader.ReadString('
')
    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,就向他打招呼,否则告诉他出去.问题是,即使输入的名字是 Alice 或 Bob,它也会告诉用户离开.

It should ask the user to tell it's name and, if he is either Alice or Bob, greet him and else tell him to get out. The problem is, that even when the entered name is Alice or Bob, it tells the User to get out.

爱丽丝:

/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

推荐答案

这是因为你的 text 正在存储 Bob

This is because your the text is storing Bob

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

One way to solve this is using strings.TrimSpace to trim the newline, eg:

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

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

或者,您也可以使用 ReadLine 代替 ReadString,例如:

Alternatively, you can also use ReadLine instead of ReadString, eg:

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

需要string(text)的原因是ReadLine会返回byte[]而不是string.

The reason why the string(text) is needed is because ReadLine will return you byte[] instead of string.

这篇关于reader.ReadString 不会删除第一次出现的 delim的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆