doumian3780 2018-10-10 00:44
浏览 114
已采纳

在Golang中冲洗stdin缓冲区?

I'm new programming with Go. I've been writing this little program that uses structures. It's a structure called user, which has as values, first name, last name and age. The problem lies when entering data, more specifically when it comes to entering the last name, this error happens: a screenshot of the error

You can see from the image that when you introduces data in the name field, ignores last name field, and jumps to age.

Having knowledge in C, this error happens when the buffer has not been flushed. (but C is a different language from Go)

As I know, Go stdin read is unbuffered. So how would you solve this problem?

Here's the code:

package main

import "fmt"

type user struct {
    name, surnm string
    age int
}

func main() {

    n := new(user)

    fmt.Print("Name? ")
    fmt.Scanf("%s", &n.name)

    fmt.Print("Last name? ")
    fmt.Scanf("%s", &n.surnm)

    fmt.Print("Age? ")    
    fmt.Scanf("%d", &n.age)

    fmt.Println(n.name)         
    fmt.Println(n.surnm)
    fmt.Println(n.age)

}

Sorry if my question is a little bit stupid, but how I said, I am new at Go.

  • 写回答

1条回答 默认 最新

  • dongye9453 2018-10-10 06:14
    关注

    This is a little difficult to reproduce on go 1.11 on Ubuntu I am guessing you are using a Microsoft operating system of some sort Microsoft have line endings of , return + newline whereas Unix-like systems have just newline only

    If I fake up an input file for your program that has line endings it does seem to skip

    Whereas an input file with only makes the program work correctly

    Adding explicit to the pattern as shown seems to fix the problem

    fmt.Print("Name? ")
    fmt.Scanf("%s", &n.name)
    
    fmt.Print("Last name? ")
    fmt.Scanf("%s", &n.surnm)
    
    fmt.Print("Age? ")
    fmt.Scanf("%d", &n.age)
    

    This is curious as the go documentation on scanf states

    In all the scanning functions, a carriage return followed immediately by a newline is treated as a plain newline ( means the same as ).

    To be fair, once the changes above are made the code behaves the same for files and files

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题