Golang 中的 Scanln 不接受空格
Scanln in Golang doesn't accept whitespace
如何使用接受空格作为输入的 Scanln
?
你不能使用 fmt
包的 Scanln()
和类似的功能来做你想做的事情,因为引用自 fmt
包文档:
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
包有意过滤掉空格,这就是它的实现方式。
而是使用 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()
函数,传递 os.Stdin
.
示例:
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
line := scanner.Text()
fmt.Printf("Input was: %q\n", line)
}
现在如果你输入 3 个空格并按 Enter,输出将是:
Input was: " "
一个更完整的示例,它会一直读取行,直到您终止应用程序或输入 "quit"
,并检查是否有错误:
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)
}
如何使用接受空格作为输入的 Scanln
?
你不能使用 fmt
包的 Scanln()
和类似的功能来做你想做的事情,因为引用自 fmt
包文档:
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
包有意过滤掉空格,这就是它的实现方式。
而是使用 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()
函数,传递 os.Stdin
.
示例:
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
line := scanner.Text()
fmt.Printf("Input was: %q\n", line)
}
现在如果你输入 3 个空格并按 Enter,输出将是:
Input was: " "
一个更完整的示例,它会一直读取行,直到您终止应用程序或输入 "quit"
,并检查是否有错误:
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)
}