Home  >  Article  >  Backend Development  >  How to Read Space-Separated Strings from a String Using Fmt.Scanln?

How to Read Space-Separated Strings from a String Using Fmt.Scanln?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 00:04:03389browse

How to Read Space-Separated Strings from a String Using Fmt.Scanln?

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!

Statement:
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