algorithm - Golang: How do I convert command line arguments to integers? -
i want create script insertion sort on arguments provided user, this:
$ insertionsort 1 2 110 39
i expect return:
[1 2 39 110]
but returns:
[1 110 2 39]
i think it's because elements in os.args array strings. so, question how convert elements of os.args array integers? here's code:
bundle main import ( "fmt" "os" "reflect" "strconv" ) func main() { := os.args[1:] := 0; <= len(a); i++ { strconv.atoi(a[i]) fmt.println(reflect.typeof(a[i])) } j := 1; j < len(a); j++ { key := a[j] := j - 1 >= 0 && a[i] > key { a[i+1] = a[i] = - 1 a[i+1] = key } } fmt.println(a) }
as heads up, when substitute
strconv.atoi(a[i])
for
a[i] = strconv.atoi(a[i])
i next error:
./insertionsort.go:14: multiple-value strconv.atoi() in single-value context
thank time!
atoi returns number , error (or nil)
parseint interprets string s in given base of operations (2 36) , returns corresponding value i. if base of operations == 0, base of operations implied string's prefix: base of operations 16 "0x", base of operations 8 "0", , base of operations 10 otherwise.
the bitsize argument specifies integer type result must fit into. bit sizes 0, 8, 16, 32, , 64 correspond int, int8, int16, int32, , int64.
the errors parseint returns have concrete type *numerror , include err.num = s. if s empty or contains invalid digits, err.err = errsyntax , returned value 0; if value corresponding s cannot represented signed integer of given size, err.err = errrange , returned value maximum magnitude integer of appropriate bitsize , sign.
you need :
var err error nums := make([]int, len(a)) := 0; < len(a); i++ { if nums[i], err = strconv.atoi(a[i]); err != nil { panic(err) } fmt.println(nums[i]) }
working illustration : http://play.golang.org/p/xdba_pszml
algorithm sorting go type-conversion command-line-arguments
No comments:
Post a Comment