How to wait for command line input in Go

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

How to wait for command line input in Go

问题

我想显示一个“>”,然后让程序等待用户在命令行中输入并按下回车键(最终将其存储为字节切片)。在Java中,我会这样做:

Scanner scanner = new Scanner(System.in);

System.out.print("> ");
String sentence = scanner.nextLine();

我尝试过一些涉及os.Argsconsole.ReadBytes('\n')bufio.NewReader(os.Stdin)的方法,但我还没有弄清楚。如果有任何建议,将不胜感激。谢谢。

英文:

I want to display a "> ", and then have the program wait for the user to type something into the command line and hit enter (and ultimately store that as a byte slice). In Java I would have done something like:

Scanner scanner = new Scanner(System.in);

System.out.print("> ");
String sentence = scanner.nextLine();

I've tried some things involving os.Args, console.ReadBytes('\n'), and bufio.NewReader(os.Stdin), but I still haven't figured it out. Any suggestions would be greatly appreciated. Thanks.

答案1

得分: 11

以下是Go代码的中文翻译:

package main

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Print("> ")
	sentence, err := buf.ReadBytes('\n')
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(string(sentence))
	}
}

希望这个翻译对你有帮助!

英文:

Some Go code would have probably been helpful so I could tell you what you did wrong. But here is how you would do this in Go:

package main

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Print("> ")
	sentence, err := buf.ReadBytes('\n')
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(string(sentence))
	}
}

huangapple
  • 本文由 发表于 2013年9月22日 03:23:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/18936662.html
匿名

发表评论

匿名网友

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

确定