douzhao2047 2013-10-23 01:52
浏览 243
已采纳

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

I am trying to get a user input in this small program. I have tried doing this several ways with the strconv.Atoi() method (my input is obviously a string, and I'm trying to convert it to an integer). Here's my first attempt:

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

and got the following error when it came to compiling:

(line 19) multiple-value strconv.Atoi() in single-value context

I then looked into Godocs and tried to figure this out for myself, and then realized that an error value is returned as well. So, I changed the

input := strconv.Atoi(inputstr)

to

input, _ := strconv.Atoi(inputstr)

Now this compiles just fine, without any errors. However, when I run the program, here's what I get:

Say something, in numbers.

0

and then it exits... What am I doing wrong? I believe this is a question about to Atoi() method, but if it's concerning the Scanln() then please correct me.

  • 写回答

1条回答 默认 最新

  • douxi3977 2013-10-23 02:56
    关注

    The problem turns out to be the Scanln. Scanln is returning an error type not a pointer because of the %s. This then leaves inputstr blank, which when given to Atoi is returning an error: strconv.ParseInt: parsing "": invalid syntax.

    Using Scanf as follows with no change to the 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)
    }
    

    Probably the simplest solution is to remove the "%s" from the Scanln.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效