2

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

2
  • 2
    If you type in -1 then - causes the fmt.Scanln(&userTicket) to exit with error, the next fmt.Scan(&name) statement doesn't block because it is fed the remaining input, i.e. 1. Commented Mar 2, 2022 at 12:16
  • Thanks for your comment. Your comment plus @Volker's answers solved my question. Commented Mar 2, 2022 at 13:26

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

I know -1 cannot be stored in an uint, could you please confirm the comment from @mkopriva is correct? "If you type in -1 then - causes the fmt.Scanln(&userTicket) to exit with error, the next fmt.Scan(&name) statement doesn't block because it is fed the remaining input, i.e. 1." . My understanding on his comment is ticket scan take "-" and scan for first name take rest of "1"
Ah, I can confirm @mkopriva was correct, fmt.Scan(&name) statement doesn't block because it is fed the remaining input, i.e. 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.