Home > Article > Backend Development > How to Parse Space-Separated Strings with fmt.Scanln in Go?
How to Parse Space-Separated Strings with fmt.scanln
fmt.scanln is a function used to read input from standard input and scan it into structured variables. However, when reading strings separated by spaces, it may encounter some unexpected behavior.
By default, fmt.scanln stops scanning at the first newline character. This can lead to situations where the user enters a string containing multiple space-separated words, but only the first word is captured.
For example, consider the following code:
<code class="go">package main import "fmt" func main() { var s string fmt.Scanln(&s) fmt.Println(s) return }</code>
When the user enters "31 of month", only "31" is captured into the s variable. This occurs because fmt.scanln stops scanning after encountering the space character, which is a whitespace character.
To resolve this issue and capture multiple space-separated words, you can do either of the following:
Use multiple fmt.Scanln statements:
<code class="go">package main import "fmt" func main() { var s1 string var s2 string fmt.Scanln(&s1, &s2) fmt.Println(s1) fmt.Println(s2) return }</code>
Use a buffered scanner:
<code class="go">package main import ( "bufio" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { s := scanner.Text() fmt.Println(s) } if err := scanner.Err(); err != nil { os.Exit(1) } }</code>
The above is the detailed content of How to Parse Space-Separated Strings with fmt.Scanln in Go?. For more information, please follow other related articles on the PHP Chinese website!