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
+11.7k Golang : Convert decimal number(integer) to IPv4 address
+10.7k Golang : Sieve of Eratosthenes algorithm
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+16.1k Golang : Convert slice to array
+14.1k Golang : Parsing or breaking down URL
+36.1k Golang : Convert(cast) int64 to string
+17.7k Golang : Put UTF8 text on OpenCV video capture image frame
+16.5k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+10.2k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+7.5k Golang : Lock executable to a specific machine with unique hash of the machine
+29.9k Golang : How to verify uploaded file is image or allowed file types
+15.2k Golang : rune literal not terminated error