Home  >  Article  >  Backend Development  >  How to Read Multiple Integers from Standard Input in Golang Without a For Loop?

How to Read Multiple Integers from Standard Input in Golang Without a For Loop?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 01:10:30470browse

How to Read Multiple Integers from Standard Input in Golang Without a For Loop?

Reading Integers Separated by Space in Golang

Question:

How to efficiently read multiple integers from standard input (stdin) and store them in an integer slice without using a for loop in Golang? For example, given the following input:

Enter the number of integers
3
Enter the integers
23 45 66

How to convert these values into an integer slice?

Answer:

Although a loop is inherently present, it's possible to achieve this without using explicit for or goto loops. Here's how:

<code class="go">package main

import "fmt"

func main() {
    fmt.Println(`Enter the number of integers`)
    var n int
    if m, err := Scan(&amp;n); m != 1 {
        panic(err)
    }
    fmt.Println(`Enter the integers`)
    all := make([]int, n)
    ReadN(all, 0, n)
    fmt.Println(all)
}

func ReadN(all []int, i, n int) {
    if n == 0 {
        return
    }
    if m, err := Scan(&amp;all[i]); m != 1 {
        panic(err)
    }
    ReadN(all, i+1, n-1)
}

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}</code>

Example Input/Output:

Enter the number of integers
3
Enter the integers
10 20 30
[10 20 30]

Optimization for Faster Input Scanning:

To enhance input scanning speed, replace the Scan function with the following optimized version:

<code class="go">func Scan(a *int) (int, error) {
    var buf [10]byte
    var ret int
    for scanned, err := fmt.Scanf("%d%s", &ret, &buf); err == nil && scanned != 2; {
        fmt.Scanf("%s", &buf)
    }
    *a = ret
    return 1, err
}</code>

The above is the detailed content of How to Read Multiple Integers from Standard Input in Golang Without a For Loop?. 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