Home > database >  GoLang fmt.Scan type error skip next fmt.Scan
GoLang fmt.Scan type error skip next fmt.Scan

Time:03-03

Am a beginner of GoLang here is a sample code from a tutorial.

func main() {
    for {
        var name string
        var email string
        var userTickets uint
        // ask user for info
        fmt.Println("Input your Name please")
        fmt.Scan(&name)

        fmt.Println("Input your Email please")
        fmt.Scan(&email)

        // ask user for number of tickets
        fmt.Println("Input number of ticket")
        if _, err := fmt.Scanln(&userTickets); err != nil {
            fmt.Println(err)
        }
    }
}

Here is an interesting thing I found: if I entered "-1" in "Input number of ticket". It will throw an error since userTickets is uint. With that err it will also put an "enter/next line" for "Input your Name please" in the next loop. The result would look like this

Input your Name please
Test
Input your Email please
Test
Input number of tickect
-1
expected integer
Input your Name please <= this input is skipped
Input your Email please

So just wondering why this heppened? How can I resolve that (without changing type from uint to int)?

CodePudding user response:

So just wondering why this heppened?

Because -1 cannot be stored in an uint.

How can I resolve that (without changing type from uint to int)?

You cannot.

(The right thing to do is not to use fmt.Scan but to always read whole lines into a string and parse the string.)

  •  Tags:  
  • go
  • Related