dpmp9359 2016-06-29 08:46
浏览 1122

Golang-读取Os.stdin输入,但不回显

In a golang program I'm reading the Os.Stdin input from a bufio.Reader.

After enter is pressed, the program reads the input and it is then printed onto the console. Is it possible to not print the input onto the console? After reading it, I process the input and reprint it (and no longer need the original input).

I read the data like this:

inputReader := bufio.NewReader(os.Stdin)
for {
    outgoing, _ := inputReader.ReadString('
')
    outs <- outgoing
}
  • 写回答

3条回答 默认 最新

  • douhao8456 2016-06-29 09:17
    关注

    I cannot think to other methods than to use ANSI escape codes to clear the terminal and move the cursor to a specific location (in your case to column 1:row 1).

    var screen *bytes.Buffer = new(bytes.Buffer)
    var output *bufio.Writer = bufio.NewWriter(os.Stdout)
    

    And here are some basic helper methods to ease your job working with terminal.

    // Move cursor to given position
    func moveCursor(x int, y int) {
        fmt.Fprintf(screen, "\033[%d;%dH", x, y)
    }
    
    // Clear the terminal
    func clearTerminal() {
        output.WriteString("\033[2J")
    }
    

    Then inside your function you need to clear the terminal and move the cursor to the first column and first row of the terminal window. At the end you have to output the computed result.

    for {
        outgoing, err := input.ReadString('
    ')
    
        if err != nil {
            break
        }
    
        if _, err := fmt.Sscanf(outgoing, "%f", input); err != nil {
            fmt.Println("Input error!")
            continue
        }
    
        // Clear console
        clearTerminal()
        moveCursor(1,1)
    
        fmt.Println(outs) // prints the computed result
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!