Reading Space-Separated Strings from a String Using Fmt.Scanln
The Scanln function, part of the fmt package, enables the reading of input from a string. However, a common issue encountered when using Scanln is obtaining only the first word when expecting multiple space-separated words.
In the example provided:
<code class="go">package main import "fmt" func main() { var s string fmt.Scanln(&s) fmt.Println(s) return }</code>
When running this code with the input "31 of month," it outputs "31" instead of the expected "31 of month." This is because Scanln treats the input as a single token, ignoring spaces.
To resolve this issue, you can utilize the following solutions:
1. Scan Multiple Variables Simultaneously
fmt Scanln accepts multiple arguments, allowing you to read multiple words simultaneously.
<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>
This code will correctly output "31" and "of month."
2. Use Bufio Scanner
The bufio package simplifies the process of reading input from a variety of sources, including strings.
<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>
With this code, you can read and print each line individually.
The above is the detailed content of How to Read Space-Separated Strings from a String Using Fmt.Scanln?. For more information, please follow other related articles on the PHP Chinese website!