Home > Article > Backend Development > How to Read Space-Separated Strings from User Input in Go?
Parsing Strings Separated by Spaces Using fmt.Scanln
When attempting to read a string from user input that contains multiple words separated by spaces, fmt.Scanln may return only the first word. To address this issue:
Understanding fmt.Scanln
fmt.Scanln operates similarly to fmt.Scan, but terminates scanning upon encountering a newline character. The newline character must follow the last item or there must be an EOF (End-of-File) indicator.
Using Scanln to Read Space-Separated Strings
To successfully read space-separated strings, specify multiple variables in the fmt.Scanln call:
<code class="go">var s1 string var s2 string fmt.Scanln(&s1, &s2)</code>
This approach assigns the first word to s1 and the second to s2.
Alternative Approach Using bufio.Scanner
Another option is to employ bufio.Scanner:
<code class="go">scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { s := scanner.Text() fmt.Println(s) }</code>
Here, scanner loops through the standard input and prints each line of input.
The above is the detailed content of How to Read Space-Separated Strings from User Input in Go?. For more information, please follow other related articles on the PHP Chinese website!