【发布时间】:2020-05-04 20:27:35
【问题描述】:
package main
import (
"bufio"
"fmt"
"os"
)
func Option1() {
fmt.Println("Option1")
}
func main() {
for true {
fmt.Println("Pleae enter text: ")
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
if text == "1" {
Option1()
}
}
}
所以我的代码最终将具有多功能示例:option1 option2 等。每次用户键入 1、2、3 等时,我都会尝试执行一个函数,但我的代码不会打印出任何内容在选项 1。
您的帮助将不胜感激。
【问题讨论】:
-
From the docs: "ReadString 读取直到输入中第一次出现 delim,返回一个包含 和包含分隔符 的数据的字符串。" (强调我的)。
-
分隔符
\n包含在ReadString 返回的值中。此外,该程序丢弃从标准输入缓冲的数据。请改用Scanner。请参阅this question 了解更多信息。 -
你也可以只检查
text[:1]的值。 -
@larsks 这在所有操作系统上都不会像您期望的那样工作。使用扫描仪。
-
for { fmt.Println(prompt); if !scanner.Scan() { break }; text := scanner.Text(); /* do something with text */}