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(&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(&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!