Scanln在Golang中不接受空格。

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

Scanln in Golang doesn't accept whitespace

问题

你可以使用Scanln函数来接受包含空格的输入。

英文:

How can I use Scanln that accepts whitespace as input?

答案1

得分: 23

你想要做的事情不能使用fmt包的Scanln()和类似的函数,因为根据fmt包的文档:

> 通过格式化动词处理的输入会被隐式地以空格分隔:除了%c动词之外的每个动词的实现都会丢弃剩余输入中的前导空格,而%s动词(以及读入字符串的%v动词)在第一个空格或换行符处停止消耗输入

fmt包有意地过滤掉空白字符,这是它的实现方式。

相反,你可以使用bufio.Scanner来读取可能包含你不想过滤掉的空格的行。要从标准输入读取/扫描,可以使用bufio.NewScanner()函数创建一个新的bufio.Scanner,并传递os.Stdin

示例:

scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
    line := scanner.Text()
    fmt.Printf("输入为:%q\n", line)
}

现在,如果你输入3个空格并按下<kbd>Enter</kbd>,输出将是:

输入为:"   "

以下是一个更完整的示例,它会一直读取行,直到你终止应用程序或输入"quit",并且还会检查是否有错误:

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    line := scanner.Text()
    fmt.Printf("输入为:%q\n", line)
    if line == "quit" {
        fmt.Println("正在退出...")
        break
    }
}
if err := scanner.Err(); err != nil {
    fmt.Println("遇到错误:", err)
}
英文:

You can't use the fmt package's Scanln() and similar functions for what you want to do, because quoting from fmt package doc:

> Input processed by verbs is implicitly space-delimited: the implementation of every verb except %c starts by discarding leading spaces from the remaining input, and the %s verb (and %v reading into a string) stops consuming input at the first space or newline character.

The fmt package intentionally filters out whitespaces, this is how it is implemented.

Instead use bufio.Scanner to read lines that might contain white spaces which you don't want to filter out. To read / scan from the standard input, create a new bufio.Scanner using the bufio.NewScanner() function, passing os.Stdin.

Example:

scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
	line := scanner.Text()
	fmt.Printf(&quot;Input was: %q\n&quot;, line)
}

Now if you enter 3 spaces and press <kbd>Enter</kbd>, the output will be:

Input was: &quot;   &quot;

A more complete example that keeps reading lines until you terminate the app or enter &quot;quit&quot;, and also checks if there was an error:

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
	line := scanner.Text()
	fmt.Printf(&quot;Input was: %q\n&quot;, line)
	if line == &quot;quit&quot; {
		fmt.Println(&quot;Quitting...&quot;)
		break
	}
}
if err := scanner.Err(); err != nil {
	fmt.Println(&quot;Error encountered:&quot;, err)
}

huangapple
  • 本文由 发表于 2017年5月8日 16:53:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/43843477.html
匿名

发表评论

匿名网友

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

确定