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

查看:80
本文介绍了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? \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,它也会告诉用户离开.

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\n

This is because your the text is storing Bob\n

解决此问题的一种方法是使用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天全站免登陆