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.

GoCli Tooling

Code

gosnippet
21 lines
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

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:`.