Home > Backend Development > Golang > How to Read Space-Separated Strings with fmt.Scanln in Go?

How to Read Space-Separated Strings with fmt.Scanln in Go?

Barbara Streisand
Release: 2024-11-03 13:15:03
Original
397 people have browsed it

How to Read Space-Separated Strings with fmt.Scanln in Go?

Using fmt.Scanln to Read Space-Separated Strings

While using fmt.Scanln(), it is common to encounter instances where desired text is truncated. Consider the following example:

<code class="go">package main

import "fmt"

func main() {
    var s string
    fmt.Scanln(&s)
    fmt.Println(s)
    return
}</code>
Copy after login

With the input "30 of month," the expected output would be "30 of month," but instead, the result is truncated to "30." This is because Scanln expects a newline character to terminate input.

Solution:

To read space-separated tokens, use the fmt Scan family:

<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 approach explicitly specifies multiple variables for input, ensuring that each token is correctly read.

Alternative Solution: bufio.Scan

Alternatively, consider using the bufio scanner:

<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

This method reads input line by line, providing greater flexibility and control over the input process.

The above is the detailed content of How to Read Space-Separated Strings with fmt.Scanln 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