I'm using a portable unzipped version of Go! Whenever I try to do a input output console implementation using Scanf (but also related functions) inserting runtime input and validating with enter results in the program behaving (it's a loop) like I inputted twice or three times. Obviously (like in C) the stdin needs to be cleared after calling the reading-function, but I don't find how to do that. I seem to be the only one with this stupid basic problem (why?)
In this endless loop -program the question is asked and answered 3 times even after my poor flush attempt:
package main
import "fmt"
import "time"
var globalBad, globalGood int
func Thread1() {
var i int
var t string
for {
fmt.Println("Please give I")
fmt.Scanf("%d", &i)
fmt.Println(t);
flush();
globalBad = i;
//fmt.Println(i);
time.Sleep(1000 * time.Millisecond);
fmt.Println("Meet globalGood %f", globalGood )
if i == 12 {return};
}
}
func Endless(){
var LocalBad int ;
for{
if LocalBad != globalBad{
LocalBad = globalBad;
globalGood = globalBad*2;
}
time.Sleep(1000 * time.Millisecond);
}
}
func flush(){
var i byte
for i > 0{
fmt.readByte(i, var j);
}
fmt.Println("Done");
}
func main() {
globalBad = 0;
go Thread1();
Endless();
}
I can't get your code to compile. The really problematic line is the fmt.readByte(i, var j)
line. There's no fmt.readByte
function and if there were it wouldn't be exported. The var j
part is just invalid.
Also, you're sharing memory between goroutines but not synchronizing in any way (like channels, for example). This can cause all kinds of strange things to happen.
Please fix your code (and preferably gofmt it) and I can give you more specific advice.