使用fmt.Sscanf报unexpected EOF?

yecz · 2022-09-21 17:23:51 · 1797 次点击

改成纯空格分隔的确实可以,但是上面的例子改成数值型也可以:

func main() {
    var (
        str    = "a=111,b=222,c=333"
        format = "a=%d,b=%d,c=%d"

        a int
        b int
        c int
    )

    if _, err := fmt.Sscanf(str, format, &a, &b, &c); err != nil {
        log.Fatal(err)
    }

    log.Println("a:", a)
    log.Println("b:", b)
    log.Println("c:", c)
}

output:

2022/09/21 17:57:21 a: 111
2022/09/21 17:57:21 b: 222
2022/09/21 17:57:21 c: 333
#4
更多评论

// Sscanf scans the argument string, storing successive space-separated // values into successive arguments as determined by the format. It // returns the number of items successfully parsed. // Newlines in the input must match newlines in the format.

#1

// Sscanf scans the argument string, storing successive space-separated

// values into successive arguments as determined by the format. It

// returns the number of items successfully parsed.

// Newlines in the input must match newlines in the format.

func Sscanf(str string, format string, a ...any) (n int, err error) {

return Fscanf((*stringReader)(&str), format, a...)

}

#2