简体   繁体   中英

Golang: How do I convert command line arguments to integers?

I want to make a script that does an insertion sort on the arguments provided by the user, like this:

    $ insertionSort 1 2 110 39

I expect it to return:

    [1 2 39 110]

But it returns:

    [1 110 2 39]

I think it's because the elements in the os.Args array are strings. So, my question is how do I convert the elements of the os.Args array into integers? Here's my code:

    package main

    import (
        "fmt"
         "os"
         "reflect"
         "strconv"
    )

    func main() {
        A := os.Args[1:]

        for i := 0; i <= len(A); i++ {
          strconv.Atoi(A[i])
          fmt.Println(reflect.TypeOf(A[i]))
        }

         for j := 1; j < len(A); j++ {
             key := A[j]
             i := j - 1
             for i >= 0 && A[i] > key {
               A[i+1] = A[i]
               i = i - 1
               A[i+1] = key
             }
          }
        fmt.Println(A)
    }

As a heads up, when I substitute

     strconv.Atoi(A[i])

For

     A[i] = strconv.Atoi(A[i])

I get the following error:

    ./insertionSort.go:14: multiple-value strconv.Atoi() in single-value context

Thank you for your time!

Atoi returns the number and an error (or nil) from

ParseInt interprets a string s in the given base (2 to 36) and returns the corresponding value i. If base == 0, the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.

The errors that ParseInt returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.

You need to do :

var err error
nums := make([]int, len(A))
for i := 0; i < len(A); i++ {
    if nums[i], err = strconv.Atoi(A[i]); err != nil {
        panic(err)
    }
    fmt.Println(nums[i])
}

Working example : http://play.golang.org/p/XDBA_PSZml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM