如何在Go中使用strconv.Atoi()方法?

Chr*_*ula 8 casting input go

我试图在这个小程序中获得用户输入.我试过用这个strconv.Atoi()方法做几个方法(我的输入显然是一个字符串,我试图将它转换为整数).这是我的第一次尝试:

package main
    import (
        "fmt"
        "strconv"
    )

    func main() {
        //fmt.Println(strconv.Itoa)
        fmt.Println("Say something, in numbers.")
        var inputstr string
        fmt.Scanln("%s", &inputstr)
        input := strconv.Atoi(inputstr)
        output := (input * 2)
        outputstr := strconv.Itoa(output)
        fmt.Println(outputstr)
    }
Run Code Online (Sandbox Code Playgroud)

并在编译时遇到以下错误:

(第19行)单值上下文中的多值strconv.Atoi()

然后我调查了Godocs并尝试自己解决这个问题,然后意识到还会返回错误值.所以,我改变了

input := strconv.Atoi(inputstr)
Run Code Online (Sandbox Code Playgroud)

input, _ := strconv.Atoi(inputstr)
Run Code Online (Sandbox Code Playgroud)

现在这个编译得很好,没有任何错误.但是,当我运行程序时,这是我得到的:

用数字说些什么.

0

然后退出......我做错了什么?我相信这是一个关于Atoi()方法的问题,但如果它涉及到Scanln()那么请纠正我.

mil*_*onb 7

问题原来是Scanln.type not a pointer由于%s,Scanln返回错误.然后这会将inputstr留空,当给予Atoi时返回错误:strconv.ParseInt: parsing "": invalid syntax.

如下使用Scanf而不改变Atoi:

func main() {
    //fmt.Println(strconv.Itoa)
    fmt.Println("Say something, in numbers.")
    var inputstr string

    //fmt.Scanln("%s", &inputstr)
    _, err := fmt.Scanf("%s", &inputstr)
    if err != nil {
        fmt.Println(err)
    }
    input, e := strconv.Atoi(inputstr)
    if e != nil {
        fmt.Println(e)
    }
    output := (input * 2)
    outputstr := strconv.Itoa(output)
    fmt.Println(outputstr)
}
Run Code Online (Sandbox Code Playgroud)

可能最简单的解决方案是从Scanln中删除"%s".