I need to read arbitrary number of inputs from stdin
. I have following code which is working fine and reads arbitrary number of input from command-line:
// Reads from command-line arguments
package main
import(
"fmt"
"os"
"strconv"
)
func main(){
for _,arg := range os.Args[1:] {
n, err := strconv.Atoi(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v
", err)
os.Exit(1)
}
fmt.Printf("%d
", n)
}
}
But, I want to change it to read from stdin
, and what I have done is following:
// Reads input from stdin
package main
import "fmt"
func main(){
var a, b, c, d int
count, err := fmt.Scan(&a, &b, &c, &d)
fmt.Printf("Arguments Read: %d
", count)
fmt.Printf("%d, %d, %d, %d
", a, b, c, d)
if err != nil {
fmt.Printf("%v
", err)
}
}
But in the second version of code I am bound to read fixed number of arguments from stdin
. How can I read arbitrary number of arguments from stdin
?
You can loop over condition and keep on reading input from stdin until that condition is satisfied. In below example if input is "exit" program finishes reading and outputs all provided arguments.
inputOpen := true
var args []string
fmt.Println("Provide argument, type exit to finish")
for inputOpen {
var arg string
var err error
if _, err = fmt.Scan(&arg); err != nil {
fmt.Printf("%v
", err)
}
if arg == "exit" {
inputOpen = false
} else {
args = append(args, arg)
}
}
fmt.Println(fmt.Sprintf("Arguments: %v", args))