How do I use the strconv.Atoi() method in Go?

17,459

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.

Share:
17,459
Chris Morris
Author by

Chris Morris

Updated on June 11, 2022

Comments

  • Chris Morris
    Chris Morris about 2 years

    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.

  • Chris Morris
    Chris Morris over 10 years
    So basically, the "%s" is just a format character that converts the input to a string?
  • miltonb
    miltonb over 10 years
    Actually, the %s is used as a format character for Sscan, but in your code its getting two errors one from the Scanf("%s",..) not liking the %s and the next from Atoi not liking an empty string.