Value input problem - Golang

Asked

Viewed 83 times

1

I’m playing an old-fashioned game where the input is a number from 1 to 9 that corresponds to the location on the field, if I enter more than 1 digit like 44 or "Asd" is given as invalid input. However when I enter with "44 4" or "a s 5 d" it counts as valid, not only as valid, but also it goes through all the values in the game loop, skipping the input step, check. And if the entry contains values considered valid, such as "a 1 5 d aa" the values in field 1 and 5 are filled in.

This is the function that takes the values and returns. I did the test with a Print, and even receiving more than 1 value, it just gives the Print in the first value of the input.

func getLocal(jogador int) string {
    var local string
    fmt.Printf("Vez do %d* jogador \n", jogador)
    fmt.Printf("Escolha: ")
    fmt.Scan(&local)
    return local
}

This is the function that checks the input.

func veriEnt(local string) bool {
    if len(local) == 1 {
         v := regexp.MustCompile("[1-9]") 
         return v.MatchString(local)
    } else {
        return false
    }
}

The main function where the game happens, as I said, when I enter more than one value, the input and verification functions are ignored.

func main() {
    clearScream()
    var jogador, rodada = 1, 1
    for true {
        showGame()
        local := getLocal(jogador)
        ok := veriEnt(local)
        if ok {
            x, y := coordenada(local)
            attCampo(x, y, jogador)
            jogador, rodada = endTurn(jogador, rodada)
        }
        clearScream()
    }
}

The tests I saw showed me that the input is not a string with spaces or a list. And that the "error" is in one of these functions lsitadas, because the other functions only generate data based on the input, and their functioning is as expected.

PS: clearScream just clears the screen, showGame shows the field on the screen and endTurn passes the turn pro approx player and add 1 on the counter of rounds.

1 answer

2


This is happening because the function fmt.Scan reads the input to the first space found.

Everything you give as input into the terminal, goes to a stream called stdin. What the function fmt.Scan makes, is to check if there is something written in stdin, if it exists, it returns a string with the contents to the first space, if it does not exist, it waits for the user to insert something.

The rest of the content continues on stdin, then if you insert something like "44 4", the fmt.Scan will read "44", and the next time it is invoked, it will immediately read the rest of the stdin and return to you the "4".

If you want to read the entire user input, you can format the reading of the Scanf using %q to read to the end of the line, as follows:

fmt.Scanf("%q", &local)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.