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

Susan Sarandon
Release: 2024-11-04 00:04:03
Original
388 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!