dongmanni6916 2018-03-21 21:07
浏览 119
已采纳

从终端输入时不输入ENTER读取SPACE

I had a CLI program which will ask user to type ENTER to continue and OTHER keys to abort.

for {
    show() // list one page

    fmt.Printf("Press ENTER to show next page, press any other key then Enter to quit")
    var input string
    fmt.Scanln(&input)
    if strings.Trim(input, " ") == "" {
        continue
    } else {
        break
    }
}

I want to improve user experience: instead of "ENTER or press something then ENTER", how can I make it "Press SPACE to show next page, press q to quit", just like Linux command "more" and others.

To make it clear:

  • The existing control to continue is "ENTER", I want to use "SPACE" (just SPACE, not SPACE+ENTER);
  • The existing control to quit is "any key + ENTER", I want to use "q" (just q, not q+ENTER)
  • 写回答

2条回答 默认 最新

  • douchenzhan3050 2018-03-21 21:21
    关注

    There is a built in shell command read -n1 -r -p "Press SPACE to show next page, press q to quit" key. Possibly you could exec that.

    For a more full featured golang solution, see github.com/nsf/termbox-go. Good example: https://www.socketloop.com/tutorials/golang-get-ascii-code-from-a-key-press-cross-platform-example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?