简体   繁体   English

Golang不处理2个操作

[英]Golang doesn't process 2 operations

I'm a new in golang and i don't understand why I can't get next code working: 我是golang的新手,我不明白为什么我无法使下一个代码正常工作:

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". 我要打印一条消息,然后在控制台中扫描用户的输入,比较输入,如果imput等于字符串“ q”,则打印messafe。 Last check doesn't work for some reasons. 由于某些原因,最后检查无效。

from TFM: 来自TFM:

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter ReadString读取直到输入中第一次出现delim为止,返回一个字符串,其中包含直到定界符(包括定界符)的数据

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). 会起作用(顺便说一句,因为输入已经是一个字符串,所以无需调用string(input) )。

Alternatively you can also trim the endline before checking, using strings.TrimRight . 另外,您还可以检查前修剪底线,用strings.TrimRight This will make the code more portable as it will work on Windows where \\r\\n is used to delimit lines. 这将使代码更加可移植,因为它将在使用\\r\\n分隔行的Windows上运行。 So do this: 这样做:

input = strings.TrimRight(input, "\r\n")
if input == "q" {
    fmt.Println("OK")
}

And I've tested this to work myself. 我已经对此进行了测试,可以自己工作。

Not_a_Golfer is correct on why its not working. Not_a_Golfer在其为何不起作用方面是正确的。 However, for simple things like reading from STDIN you're better off using Scanner: 但是,对于简单的事情,例如从STDIN读取,最好使用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) 无论输入来自何处(Windows命令提示符,Linux / OSX上的终端等),这都将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM