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

在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

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

报告相同问题?