ridthyself
ridthyself

Reputation: 839

Inconsistent behavior in Go switch case

This is very unusual: given the same input, Go will behave differently at random.

package main

import "fmt"

func main() {

    var i string

    fmt.Scanf("%s\n", &i)
    fmt.Println(i)

    switch i {
    case "a":
        fmt.Println("good")
    case "b":
        fmt.Println("not good")
    default:
        fmt.Println("bad")
    }
}

in Command prompt I run

go run test.go

then I type

"a <enter>"

sometimes getting:

a
a
good

and randomly (about half the time) doing the same thing yields:

a
t
bad

The installation is go1.3.3.windows-amd64.msi on Windows 7 Any idea what's going on here?

Upvotes: 1

Views: 184

Answers (2)

peterSO
peterSO

Reputation: 166815

I'm unable to reproduce your error.

Don't ignore errors. For example,

package main

import "fmt"

func main() {
    var i string
    n, err := fmt.Scanf("%s\n", &i)
    if err != nil || n != 1 {
        fmt.Println(n, err)
    }
    fmt.Println(i)
    switch i {
    case "a":
        fmt.Println("good")
    case "b":
        fmt.Println("not good")
    default:
        fmt.Println("bad")
    }
}

Output:

C:\>go version
go version go1.3.3 windows/amd64
C:\gopath\src\so>go run test.go
a
a
good
C:\gopath\src\so>go run test.go
b
b
not good
C:\gopath\src\so>go run test.go
t
t
bad

Upvotes: 1

VonC
VonC

Reputation: 1328022

Just in case this is an eol (end of line) issue, try:

fmt.Scanf("%s\r\n", &i)

This is mentioned in "How do I use fmt.Scanf in Go":

this is because of the different line endings.
The windows uses carriage return and line feed('\r\n') as a line ending.
the Unix uses the line feed('\n')

Upvotes: 3

Related Questions