Golang : How to check if input from os.Args is integer?
While coding out the Ackermann codes, I need to check if the input parameters are in numeric and not some alphabet characters.
Golang's os.Args[]
function will return the result as string type and I need to check if the input parameters are indeed numeric and not alphabet.
To do that, use the strconv.ParseInt()
function to convert the parameters to integer and if it failed, prompt error and abort further execution.
// convert input (type string) to integer
first, err := strconv.ParseInt(os.Args[1], 10, 0)
if err != nil {
fmt.Println("First input parameter must be integer")
os.Exit(1)
}
second, err := strconv.ParseInt(os.Args[2], 10, 0)
if err != nil {
fmt.Println("Second input parameter must be integer")
os.Exit(1)
}
Example test results :
./ackermnn 3 abc
Second input parameter must be integer
./ackermnn a2b 2
First input parameter must be integer
Full example at https://www.socketloop.com/tutorials/golang-ackermann-function-example Reference :
https://www.socketloop.com/tutorials/golang-ackermann-function-example
See also : Golang : Ackermann function example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11k CodeIgniter : How to check if a session exist in PHP?
+5.8k nginx : force all pages to be SSL
+13.4k Golang : Set image canvas or background to transparent
+4.7k Javascript : How to get width and height of a div?
+18.7k Golang : Read input from console line
+15.7k Golang : Read large file with bufio.Scanner cause token too long error
+9.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+19.7k Golang : How to run your code only once with sync.Once object
+12.7k Golang : Get terminal width and height example
+5k PHP : See installed compiled-in-modules