How to read from user input without the \n ?

blov · · 461 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>How to read from user input without the \n ?</p> <pre><code> reader := bufio.NewReader(os.Stdin) fmt.Print(&#34;Enter text: &#34;) port, _ = reader.ReadString(&#39;\n&#39;) port = strings.Replace(port, &#34;\n&#34;, &#34;&#34;, -1) </code></pre> <p>here : port, _ = reader.ReadString(&#39;\n&#39;)</p> <p>thanks</p> <hr/>**评论:**<br/><br/>exch: <pre><p>You can remove the newlines with <a href="https://golang.org/pkg/strings/#TrimSpace" rel="nofollow">strings.TrimSpace</a>, or try parsing with <a href="https://golang.org/pkg/fmt/#Fscanf" rel="nofollow">fmt.Fscanf</a> and friends.</p></pre>bussiere: <pre><p>thks</p></pre>f00b4z: <pre><p>Maybe try with</p> <pre><code>bufio.NewScanner(os.Stdin) </code></pre></pre>bussiere: <pre><p>i want to read an input and newScanner doesn&#39;t seems to work</p></pre>f00b4z: <pre><p>I meant</p> <pre><code>scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Printf(&#34;%s&#34;, scanner.Text()) } </code></pre></pre>epiris: <pre><p>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. </p></pre>1lann: <pre><p>A short, fast approach would be to use a slice operation.</p> <p><code>port = port[:len(port)-1]</code></p></pre>

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

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