Home > Backend Development > Golang > How to Read Space-Separated Strings from User Input in Go?

How to Read Space-Separated Strings from User Input in Go?

Susan Sarandon
Release: 2024-11-04 07:48:01
Original
538 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template