英文:
Golang doesn't process 2 operations
问题
我是一个新手,我不明白为什么下面的代码不能正常工作:
func ListApps(){
fmt.Printf("\nPress Q to go back..\n")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
if string(input) == "q" {
fmt.Printf("OK")
}
}
我想打印一条消息,然后在控制台中扫描用户的输入,比较输入并在输入等于字符串"q"时打印消息。最后的检查由于某些原因不起作用。
英文:
I'm a new in golang and i don't understand why I can't get next code working:
func ListApps(){
fmt.Printf("\nPress Q to go back..\n")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
if string(input) == "q" {
fmt.Printf("OK")
}
}
I want to print a message, then scan user's input in console, compare input and print messafe if imput equals string "q". Last check doesn't work for some reasons.
答案1
得分: 5
从TFM:
> ReadString 会读取输入中第一个出现的分隔符之前的数据,包括分隔符本身在内,返回一个包含这些数据的字符串。
你在比较字符串时没有包括分隔符。
所以只需要这样做:
if input == "q\n" {...}
就可以了(顺便说一下,不需要调用 string(input)
,因为 input 已经是一个字符串)。
另外,你也可以在检查之前修剪换行符,使用 strings.TrimRight
。这样可以使代码更具可移植性,因为它可以在使用 \r\n
作为行分隔符的 Windows 上工作。所以可以这样做:
input = strings.TrimRight(input, "\r\n")
if input == "q" {
fmt.Println("OK")
}
我已经测试过这个方法可以正常工作。
英文:
from TFM:
> ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter
You are comparing the string without the delimiter.
So just doing:
if input == "q\n" {...}
would work (BTW no need to call string(input)
as input is already a string).
Alternatively you can also trim the endline before checking, using strings.TrimRight
. This will make the code more portable as it will work on Windows where \r\n
is used to delimit lines. So do this:
input = strings.TrimRight(input, "\r\n")
if input == "q" {
fmt.Println("OK")
}
And I've tested this to work myself.
答案2
得分: 2
Not_a_Golfer在解释为什么它不起作用时是正确的。然而,对于像从STDIN读取这样简单的事情,最好使用Scanner:
func ListApps(){
fmt.Printf("\n按Q返回..\n")
reader := bufio.NewScanner(os.Stdin)
reader.Scan() // 这一行扫描STDIN以获取输入
// 错误检查...
if err := scanner.Err(); err != nil {
panic(err)
}
// 要访问扫描器获取的内容,您可以使用scanner.Text()(在这种情况下是reader.Text())
if reader.Text() == "q" {
fmt.Printf("OK")
}
}
这将在输入的来源(Windows命令提示符、Linux/OSX上的终端等)上正常工作。
英文:
Not_a_Golfer is correct on why its not working. However, for simple things like reading from STDIN you're better off using Scanner:
func ListApps(){
fmt.Printf("\nPress Q to go back..\n")
reader := bufio.NewScanner(os.Stdin)
reader.Scan() // this line scans the STDIN for input
// error checking...
if err := scanner.Err(); err != nil {
panic(err)
}
// To access what the scanner got, you use scanner.Text() (reader.Text() in this case)
if reader.Text() == "q" {
fmt.Printf("OK")
}
}
This will work, regardless of where the input is from (windows command prompt, terminal on linux/OSX, etc)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论