1

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?

2 Answers 2

3

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')

Sign up to request clarification or add additional context in comments.

1 Comment

I rewrote the Scanf as you said, but it does not change the output. I did however isolate it further: If I call "go run test.go" and immediately enter the value 'a', before it finishes compiling, it registers as a 't' for some reason. Odd behavior, likely caused by the compiler/linker and has nothing to do with the language specification.
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.