func main() {
var (
str = "a=aaa,b=bbb,c=ccc"
format = "a=%s,b=%s,c=%s"
a string
b string
c string
)
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:18:41 unexpected EOF
这是什么问题?
有疑问加站长微信联系(非本文作者)

// 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.
// 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) {
}
当你执行下面代码会发现,第一个
a
把剩余所有字符串都获取了你可以增加空格,因为
scanf
默认都是已空格或者制表符之类的作为分隔,下面这种方式需要两种字符串都已空格分开下面方法我将扫描分隔符改为逗号,完全满足你的需求
我又修改了下,感觉把类型改为自定义使用起来比较麻烦。这下更完美了。
@Mericusta @yecz
改成纯空格分隔的确实可以,但是上面的例子改成数值型也可以:
output:
大佬太棒了👍👍👍
学到了,厉害