英文:
How to wait for command line input in Go
问题
我想显示一个“>”,然后让程序等待用户在命令行中输入并按下回车键(最终将其存储为字节切片)。在Java中,我会这样做:
Scanner scanner = new Scanner(System.in);
System.out.print("> ");
String sentence = scanner.nextLine();
我尝试过一些涉及os.Args
、console.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))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论