英文:
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("Input was: %q\n", line)
}
Now if you enter 3 spaces and press <kbd>Enter</kbd>, 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论