1

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) [-->]:
6
  • 1
    Your code works for me, on my machine, with 5 as the input for base and foo for mode, without the behaviour you described. Are you sure you, on your machine, can reproduce the error with the code in the question? and with the same input? If you really do get the weird behaviour then try checking the errors returned from Scanf. Commented Mar 21, 2021 at 14:29
  • 1
    imgur.com/a/cWGETnp Commented Mar 21, 2021 at 14:37
  • I'm just about to try it in a different terminal emulator. Commented Mar 21, 2021 at 14:39
  • 2
  • 1
    The \n one work for me. Odd that it still worked on linux though. Commented Mar 21, 2021 at 15:10

2 Answers 2

1

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)
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this fixes the issue. I think that it may be because of the windows terminal, as it works on mac and linux on all of the terminal emulators I've tried.
0

You can use fmt.Scanln(&base) instead of fmt.Scanf("%d", &base):

import "fmt"

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

Or line, _ := bufio.NewReader(os.Stdin).ReadString('\n') is a good alternative to reading the whole line.

For fmt.Scanf() newlines in the input must match newlines in the format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.