Sscanf Parses Structured Strings
Sscanf applies a format template to unstructured input, filling pointer arguments and returning the matched count plus an error instead of panicking.
Code
package main
import "fmt"
func main() {
// Sscanf 按格式模板拆解字符串:模板里的字面量必须逐字符匹配
var width, height int
n, err := fmt.Sscanf("box 120x80", "box %dx%d", &width, &height)
fmt.Println("box:", n, width, height, err == nil)
// %f 与 %s 组合:数值与单位一次拆出
var grams float64
var unit string
n, err = fmt.Sscanf("250.5kg", "%f%s", &grams, &unit)
fmt.Println("weight:", n, grams, unit, err == nil)
// 不匹配的输入返回已解析项数与错误,而不是 panic
var a, b int
n, err = fmt.Sscanf("7", "%d,%d", &a, &b)
fmt.Println("partial:", n, a, err != nil)
}Where the work happens
Sscanf Parses Structured Strings comes down to the function main.
Putting it to use
Running the file prints labeled results such as box:, weight:, partial: — each operation’s effect is visible in the output.
Core lines
n, err := fmt.Sscanf("box 120x80", "box %dx%d", &width, &height)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Sscanf Parses Structured Strings print when run?
- Execute the whole file; each printed line is prefixed with a label like `box:`, `weight:`, `partial:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.