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

huangapple go评论97阅读模式
英文:

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

问题

我想编写一个脚本,对用户提供的参数进行插入排序,就像这样:

    $ insertionSort 1 2 110 39

我希望它返回:

    [1 2 39 110]

但实际返回的是:

    [1 110 2 39]

我认为这是因为os.Args数组中的元素是字符串。所以,我的问题是如何将os.Args数组的元素转换为整数?这是我的代码:

    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)
    }

顺便提一下,当我将

    strconv.Atoi(A[i])

替换为

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

时,我得到以下错误:

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

谢谢你的时间!

英文:

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 (
        &quot;fmt&quot;
         &quot;os&quot;
         &quot;reflect&quot;
         &quot;strconv&quot;
    )

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

        for i := 0; i &lt;= len(A); i++ {
	      strconv.Atoi(A[i])
	      fmt.Println(reflect.TypeOf(A[i]))
        }
     
         for j := 1; j &lt; len(A); j++ {
	         key := A[j]
	         i := j - 1
	         for i &gt;= 0 &amp;&amp; A[i] &gt; 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

得分: 10

Atoi 函数从字符串中解析出一个数字和一个错误(或者是nil)。

  • ParseInt 函数将字符串 s 解释为给定进制(2 到 36)的值 i,并返回该值。如果 base == 0,则进制由字符串的前缀决定:对于 "0x",进制为 16;对于 "0",进制为 8;否则进制为 10。
  • bitSize 参数指定结果必须适应的整数类型。bitSize 值为 0、8、16、32 和 64 分别对应 int、int8、int16、int32 和 int64。
  • *ParseInt 返回的错误具有具体类型 NumError,并且包含 err.Num = s。如果 s 为空或包含无效的数字,则 err.Err = ErrSyntax,返回值为 0; 如果 s 对应的值无法用给定大小的有符号整数表示,则 err.Err = ErrRange,返回值为适当 bitSize 和符号的最大幅度整数。

你需要做的是:

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])
}

工作示例:http://play.golang.org/p/XDBA_PSZml

英文:

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 &lt; 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

huangapple
  • 本文由 发表于 2014年6月20日 11:09:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/24319352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定