英文:
Sscanf of multiple string fields in golang
问题
我正在尝试使用sscanf来解析多个字符串字段。以下是一个示例代码片段:
package main
import "fmt"
func main() {
var name, currency string
_, err := fmt.Sscanf("transaction benson: dollars", "transaction %s: %s", &name, ¤cy)
fmt.Println(err, name, currency)
}
输出结果为:
input does not match format benson:
程序已退出。
英文:
I am trying to use sscanf to parse multiple string fields. Here is an example code snippet:
package main
import "fmt"
func main() {
var name, currency string
_, err := fmt.Sscanf("transaction benson: dollars", "transaction %s: %s", &name, &currency)
fmt.Println(err, name, currency)
}
The output is
input does not match format benson:
Program exited.
答案1
得分: 11
%s
是贪婪的,会一直读取到下一个空格,这意味着它会读取冒号。在处理完 %s
后,它尝试扫描冒号,但是等等,冒号已经被读取了,下一个字符实际上是一个空格,而不是冒号!所以它失败了。
在 C 语言中,你可以通过使用 %[^:]
而不是 %s
来解决这个问题,但是似乎 Go 语言不支持这样的写法。你可能需要找到一种在不使用 Sscanf
的情况下解析字符串的方法。
英文:
%s
is greedy and gobbles up to the next space, which means it eats up the colon. After processing the %s
, it then tries to scan in the colon, but wait, that’s already been consumed, and the next character is actually a space, not a colon! So it fails.
In C you’d get around this by using %[^:]
rather than %s
, but it appears Go doesn’t support this. You might need to find some way to parse your string without Sscanf
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论