douzhuo2722 2014-06-20 03:09
浏览 156

Golang:如何将命令行参数转换为整数?

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!

  • 写回答

1条回答 默认 最新

  • dousong2023 2014-06-20 03:13
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看