Scanln in Golang doesn't accept whitespace

倾然丶 夕夏残阳落幕 提交于 2019-12-02 05:23:07

问题


How can I use Scanln that accepts whitespace as input?


回答1:


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("Input was: %q\n", line)
}

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

Input was: "   "

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)
}


来源:https://stackoverflow.com/questions/43843477/scanln-in-golang-doesnt-accept-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!