GoLang fmt.Scan type error skip next fmt.Scan


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.Println("Input your Email please")

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

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
Input your Email please
Input number of tickect
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)?


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

Answered By – Volker

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.