简体   繁体   中英

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:

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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