简体   繁体   English

在 Go 中清除缓冲区

[英]Clearing Buffer in Go

I'm new to Golang and while I'm trying to get consecutive input, The first scanf() gets the input and the remaining scanf() are omitted我是 Golang 的新手,当我尝试获取连续输入时,第一个 scanf() 获取输入,其余的 scanf() 被省略

Eg:例如:

 fmt.Println("Enter A: ")
  fmt.Scanf("%d",a)
  fmt.Println("Enter B: ")
  fmt.Scanf("%d",b)

In this, the first Scanf works while the second one doesn't get any input在这种情况下,第一个 Scanf 工作,而第二个没有任何输入

Use scan instead of scanf since you are trying to take int,使用 scan 而不是 scanf 因为您正在尝试使用 int,

    var a, b int    
    fmt.Println("Enter A: ")
    fmt.Scan(&a)
    fmt.Println("Enter B: ")
    fmt.Scan(&b)

If you want a string input,如果你想要一个字符串输入,

    reader := bufio.NewReader(os.Stdin)
    var a,b string
    fmt.Println("Enter A: ")
    a, _ := reader.ReadString("\n")
    fmt.Println("Enter B: ")
    b, _ := reader.ReadString("\n")

I think you made a typo:我想你打错了:

fmt.Println("Enter B: ) 

fmt.Println("Enter B: ")

Notice the difference?注意到区别了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM