How to read from user input without the \n ?

blov · 2017-03-13 06:00:14 · 601 次点击    
这是一个分享于 2017-03-13 06:00:14 的资源,其中的信息可能已经有所发展或是发生改变。

How to read from user input without the \n ?

        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter text: ")
        port, _ = reader.ReadString('\n')
        port = strings.Replace(port, "\n", "", -1)

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

thanks


评论:

exch:

You can remove the newlines with strings.TrimSpace, or try parsing with fmt.Fscanf and friends.

bussiere:

thks

f00b4z:

Maybe try with

bufio.NewScanner(os.Stdin)
bussiere:

i want to read an input and newScanner doesn't seems to work

f00b4z:

I meant

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    fmt.Printf("%s", scanner.Text())
}
epiris:

I think what you may be asking is to get input characters before a newline is entered? Stdin will be line buffered if it is attached to a terminal, you will want to use the vt100 interface for finer control of user input on Linux. You can do this multiple ways, interact with /dev/tty directly, exec stty, or just search for a library to do these things for you (what I suggest) for a more portable general approach.

1lann:

A short, fast approach would be to use a slice operation.

port = port[:len(port)-1]


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

601 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传