Go | 从键盘请求数据

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

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!")

}

huangapple
  • 本文由 发表于 2022年9月17日 01:53:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/73748645.html
匿名

发表评论

匿名网友

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

确定