Reading Console Input Single Multiline Golang
How to read command line input in golang#
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// reading single digit
var number int
fmt.Scanf("%d", &number)
// reading multiple digits
var inputs = make([]int, number)
for i, _ := range inputs {
fmt.Scanf("%d", &inputs[i])
}
fmt.Println("input =>", number)
fmt.Println("Numbers =>", inputs)
// Reading single line
reader := bufio.NewReader(os.Stdin)
line, _ := reader.ReadString('\n')
fmt.Println("input => ", line)
// Reading multiple line
stringSlice := make([]string, 2)
scanner := bufio.NewScanner(os.Stdin)
for i := 0; i < 2; i++ {
scanner.Scan()
stringSlice[i] = string(scanner.Bytes())
}
fmt.Println(stringSlice)
}
Reading inputs from command line is very useful when you are building any console app.
As you can see in the above programme. we have read single digit, multiple digit , single line and multiple line.
There are useful packages available to read from command line like buffered reader, scanner.
Previous Post
Singleton Pattern in Golang
Next Post
Search User Based on Latlong With Distance Golang Mongodb
comments powered by Disqus