英文:
Go | request data from the keyboard
问题
我找不到如何在GO语言中“从键盘请求数据”。
或者说,我找到了。但是我找到的方法并没有完全起作用。以下是代码:
fmt.Println("input : ")
var command string
fmt.Scanln(&command)
关键是我需要获取整行输入,但由于某种原因,空格会分隔请求。
它还会删除下一个单词的字母吗?
Python有一个很酷的东西叫做input。
英文:
I can't find how to request data from the keyboard
on GO.
Or rather, I found it. But what I found did not work fully. Here is the code:
fmt.Println("input : ")
var command string
fmt.Scanln(&command)
The bottom line is that I have to get the whole line and for some reason a space separates the request.
Also removes the letter of the next word?
Python has such a cool thing called input.
答案1
得分: 0
使用bufio.Scanner
读取os.Stdin
:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
readLine := func() (ln string, ok bool) {
for {
fmt.Print("? ")
if ok = scanner.Scan(); !ok {
break
}
if ln = scanner.Text(); ln != "" {
break
}
fmt.Println("您没有输入任何文本。")
}
return ln, ok
}
fmt.Println("请在提示处输入一些文本。输入 'exit' 退出。")
for ln, ok := readLine(); ok; ln, ok = readLine() {
fmt.Printf("您输入的是:%q\n", ln)
if ln == "exit" {
break
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
fmt.Println("再见!")
}
希望对你有帮助!
英文:
Use a bufio.Scanner
on os.Stdin
:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
readLine := func() (ln string, ok bool) {
for {
fmt.Print("? ")
if ok = scanner.Scan(); !ok {
break
}
if ln = scanner.Text(); ln != "" {
break
}
fmt.Println("You didn't enter any text.")
}
return ln, ok
}
fmt.Println("Please enter some text at the prompt. Type 'exit' to quit.")
for ln, ok := readLine(); ok; ln, ok = readLine() {
fmt.Printf("You entered: %q\n", ln)
if ln == "exit" {
break
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
fmt.Println("Goodbye!")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论