Search code examples
goinputscanf

Go program not waiting for input with scanf


I've found some sort of similar problems in c, but the solutions are c specific. package main

Here is a minimum working example of the code

import "fmt"

func main() {
  var mode string
  var base int
  for {
    fmt.Printf("(Base) [-->]: ")
    fmt.Scanf("%d", &base)
    fmt.Printf("(Mode) [-->]: ")
    fmt.Scanf("%s", &mode)
  }
}

My issue is that after asking for the mode input, it doesn't wait for input, and immediately skips to the beginning of the loop. Something like this:

(Base) [-->]: 5
(Mode) [-->]: (Base) [-->]:

Solution

  • I had the same problem, changefmt.Scanf("%d", &base) to fmt.Scanf("%d \n", &base). I think it's connected to output of Scanf() where extra newline not being consumed by first scanf. Above code may still work in some device without any errors.

    import "fmt"
    
    func main() {
      var mode string
      var base int
      for {
        fmt.Printf("(Base) [-->]: ")
        fmt.Scanf("%d \n", &base)
        fmt.Printf("(Mode) [-->]: ")
        fmt.Scanf("%s \n", &mode)
      }
    }