【问题标题】:using Scanf + input + enter makes for double input from stdin, how to flush?使用 Scanf + input + enter 从标准输入进行双重输入,如何刷新?
【发布时间】:2012-08-22 08:19:15
【问题描述】:

我使用的是便携式解压版 Go!每当我尝试使用 Scanf(以及相关函数)进行输入输出控制台实现时,插入运行时输入并使用 enter 进行验证时,程序的行为(它是一个循环)就像我输入了两次或三次一样。显然(就像在 C 中一样)调用读取函数后需要清除标准输入,但我不知道该怎么做。我似乎是唯一一个遇到这个愚蠢的基本问题的人(为什么?)

在这个无休止的循环程序中,即使在我糟糕的刷新尝试之后,这个问题也会被问和回答 3 次:

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();



}

【问题讨论】:

  • Endless 可以写成 select {},但如果你只是调用 Thead1(),而不是在 goroutine 中将其分离出来,你就不需要无限循环了。
  • 另外,请修正您的代码以便编译。

标签: io go stdin


【解决方案1】:

我无法编译您的代码。真正有问题的行是fmt.readByte(i, var j) 行。没有fmt.readByte 函数,如果有它就不会被导出。 var j 部分无效。

此外,您在 goroutine 之间共享内存,但不以任何方式同步(例如通道)。这会导致各种奇怪的事情发生。

请修正你的代码(最好是 gofmt),我可以给你更具体的建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2011-01-08
    相关资源
    最近更新 更多