golang reading text input over more than one line and stop ctrl+s

huangapple go评论78阅读模式
英文:

golang reading text input over more than one line and stop ctrl+s

问题

如何在golang中读取多行控制台输入?

reader := bufio.NewReader(os.Stdin)

fmt.Println("Enter Text:")

text, _ := reader.ReadString('\n')

我应该如何更改ReadString(???)以便在用户按下<kbd>ctrl</kbd>+<kbd>s</kbd>时停止读取?换行符(\n)必须保留为输入的一部分。

是否有一些库/框架可以实现这个功能?

感谢您的帮助。

祝好。

英文:

How can I read more than one line in golang, console input.

reader := bufio.NewReader(os.Stdin)

fmt.Println(&quot;Enter Text:&quot;)

text, _ := reader.ReadString(&#39;\n&#39;)

How I must change ReadString(???) to stop reading if the user hit: <kbd>ctrl</kbd>+<kbd>s</kbd>
The New Line (\n) must remain a constituent of the input.

Is there some library/framework for that?

Thanks for every help.

Cheers

答案1

得分: 3

以下是对Linux的答案(也适用于其他*nix平台):

Ctrl+S是一个控制字符DC3,它表示“XOFF,停止发送”。如果按下Ctrl+S,终端会冻结。

Ctrl+Q是一个控制字符DC1,它表示“XON,继续发送”,在按下Ctrl+S后需要按下Ctrl+Q来解冻。

要使用Ctrl+S,首先使用stty -ixon禁用XON/XOFF(可能在启动脚本中)。
在禁用XON/XOFF之后,以下是示例代码(DC3在ASCII表中的十六进制为13/十进制为19):

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Println("输入文本:")
    text, _ := reader.ReadString('\x13')
    fmt.Println(text)
}

希望对你有帮助!

英文:

Here is an answer for Linux (and could work for other *nix platforms)

Ctrl+S is a control character DC3, it means "XOFF, stop sending". If you press Ctrl+S the terminal would freeze.

Ctrl+Q is a control character DC1, it mean "XON, continue sending", it is necessary after Ctrl+S to unfreeze.

To use the Ctrl+S, first disable XON/XOFF with stty -ixon (maybe in in startup script)
After disabling XON/XOFF, the sample code is following (DC3 is HEX:13/DEC:19 in ASCII table);

package main

import (
    &quot;bufio&quot;
    &quot;fmt&quot;
    &quot;os&quot;
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Println(&quot;Enter Text:&quot;)
    text, _ := reader.ReadString(&#39;\x13&#39;)
    fmt.Println(text)
}

huangapple
  • 本文由 发表于 2014年12月27日 22:25:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/27668146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定