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
+4.1k JQuery : Calling a function inside Jquery(document) block
+35.4k Golang : Display float in 2 decimal points and rounding up or down
+7.6k Golang: Prevent over writing file with md5 hash
+6.4k Golang : Use modern ciphers only in secure connection
+7.2k Golang : Multiplexer with net/http and map
+32.2k Golang : Smarter Error Handling with strings.Contains()
+9.1k Golang : Setting variable value with ldflags
+8.9k Golang : Resumable upload to Google Drive(RESTful) example
+8.4k Golang : Create and shuffle deck of cards example
+9.4k Golang : cannot assign type int to value (type uint8) in range error
+21.5k Golang : Round float to precision example
+20.8k Golang : Setting up/configure AWS credentials with official aws-sdk-go