reader.ReadString 不会删除第一次出现的 delim
时间:2023-03-08
浏览:312
作者:佚名
golang学习网今天将给大家带来《reader.ReadString 不会删除第一次出现的 delim》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到golang等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
问题内容
我写了一个简单的 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,请向他打招呼,否则告诉他离开。问题是,即使输入的名字是 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
正确答案
这是因为您的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.
到这里,我们也就讲完了《reader.ReadString 不会删除第一次出现的 delim》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于golang的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
