How can I use Scanln
that accepts whitespace as input?
Golang中的Scanln不接受空格
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- drn1008 2017-05-08 09:12关注
You can't use the
fmt
package'sScanln()
and similar functions for what you want to do, because quoting fromfmt
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 newbufio.Scanner
using thebufio.NewScanner()
function, passingos.Stdin
.Example:
scanner := bufio.NewScanner(os.Stdin) if scanner.Scan() { line := scanner.Text() fmt.Printf("Input was: %q ", 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 ", line) if line == "quit" { fmt.Println("Quitting...") break } } if err := scanner.Err(); err != nil { fmt.Println("Error encountered:", err) }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报