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 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能