To read input argument numbers and print their sum in Go, we need to use the os
package to access the command-line arguments. Here's an example program:
main.go272 chars21 lines
In this program, we use a for
loop to iterate over the command-line arguments starting from the second argument (os.Args[1:]
). For each argument, we use the strconv.Atoi()
function to convert it to an integer. If the conversion fails (i.e., the argument is not a valid number), we print an error message and continue to the next argument.
Otherwise, we add the number to a running total called sum
. Finally, we print the sum using fmt.Printf()
.
To run this program, we can pass any number of space-separated integers as command-line arguments:
main.go29 chars3 lines
If any of the arguments are not valid numbers, they will be skipped with an error message:
main.go89 chars5 lines
gistlibby LogSnag