Golang中的Scanln不接受空格 [英] Scanln in Golang doesn't accept whitespace

查看:408
本文介绍了Golang中的Scanln不接受空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用接受空白作为输入的Scanln?

How can I use Scanln that accepts whitespace as input?

推荐答案

您不能使用 fmt 包的Scanln()以及您要执行的类似功能,因为引用了fmt包doc:

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

由动词处理的输入是隐式用空格分隔的:除%c之外的所有动词的实现均从其余输入中丢弃前导空格开始,并将%s动词(和%v读入字符串)在第一个空格或换行符处停止使用输入.

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.

fmt软件包有意过滤掉空格,这是它的实现方式.

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

请改为使用 bufio.Scanner 来读取可能包含空白的行,不想过滤掉.要从标准输入中读取/扫描,请使用 bufio.NewScanner() 创建新的bufio.Scanner函数,传递os.Stdin.

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.

示例:

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

现在,如果您输入3个空格并按 Enter ,则输出为:

Now if you enter 3 spaces and press Enter, the output will be:

Input was: "   "

一个更完整的示例,该示例会不断读取行,直到您终止应用程序或输入"quit",并且还会检查是否存在错误:

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

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

这篇关于Golang中的Scanln不接受空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆