2

I created a very small game of number guessing in Go. The thing is, it executes differently under Windows and under Linux. By executing it on Ubuntu for example, everything works just fine. But when I try to start it under Windows, it compiles just fine but during execution when I enter something (for example 5) it prints me twice "Smaller than random num"or "Bigger than random num". I have no idea why it happens.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main () {
    var number int //declaration
    var tries int = 0
    random_number := random(1, 9) //gets random number
    for ; ;tries++ {
                //fmt.Printf("Enter your prediction: ")
                fmt.Scanf("%v",&number)
                if number == random_number {
                        break;
                } else if number<random_number{
                            fmt.Printf("Smaller than random num\n")
                } else {
                            fmt.Printf("Bigger than random num\n")
                }
         }
    fmt.Printf("You guessed correctly in %v tries",tries)

}

 func random(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}
8
  • 1
    This is the execution under Windows 10: 4 Smaller than random num Smaller than random num 5 Smaller than random num Smaller than random num 7 Smaller than random num Smaller than random num 9 Bigger than random num Bigger than random num 8 You guessed correctly in 8 tries Commented May 7, 2017 at 8:57
  • With Scanln it is an infinite loop, printing smaller than random num Commented May 7, 2017 at 11:50
  • And is there any error returned (is it a value != nil?) Both Scanf and Scanln return the number of items processed and an error value that you should be checking. Commented May 7, 2017 at 12:19
  • No error is returned. Or at least not in the terminal (command prompt). Commented May 7, 2017 at 12:29
  • You assigned the two values returned by those functions and compared the error returned to ensure it's equal to nil, right? If it's not nil, there was a possible problem. See this example Commented May 7, 2017 at 12:40

1 Answer 1

2

Newlines are different in Linux and Windows, and thus your program behaves differently.

See this issue: https://github.com/golang/go/issues/5391

To fix this, you can replace your Scanf with this (note the "\n" at the end):

fmt.Scanf("%v\n",&number)
Sign up to request clarification or add additional context in comments.

1 Comment

@ChronoKitsune you're right - go version go1.8.1 windows/amd64,never would've thought of that, thanks.

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.