我意识到以下内容仅读取单个单词字符串 -
fmt.Scan(&sentence)
Run Code Online (Sandbox Code Playgroud)
如何读取多单词字符串 - 例如,该字符串sentence应该存储包含多个单词的字符串。
人们InputReader还可以使用它从控制台扫描和打印多个单词。
解决方案代码如下:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
inputReader := bufio.NewReader(os.Stdin)
input, _ := inputReader.ReadString('\n')
fmt.Println(input)
}
Run Code Online (Sandbox Code Playgroud)
控制台输入:
我们走吧!!!
控制台输出:
我们走吧!!!
笔记:
要运行 GOLANG 程序,请打开命令提示符或 powershell,导航到程序文件所在的目录并输入以下命令:
go run file_name.go
Run Code Online (Sandbox Code Playgroud)
您的问题涉及扫描空格分隔的输入。fmt.Scan https://golang.org/pkg/fmt/#Scan的定义指出:
Scan scans text read from standard input, storing successive space-
separated values into successive arguments. Newlines count as space.
It returns the number of items successfully scanned. If that is less
than the number of arguments, err will report why.
Run Code Online (Sandbox Code Playgroud)
因此,根据定义,将扫描输入,直到找到第一个空格。要进行扫描,假设您在命令行上点击 a 之前,您可以使用Go 中 stdin 的\n注释扫描空间中的代码:
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
return scanner.Text()
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
Run Code Online (Sandbox Code Playgroud)
此线程也可能有用:https://groups.google.com/forum/#! topic/golang-nuts/r6Jl4D9Juw0