Files
bulma/scan_demo.go
T

38 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"bytes"
"fmt"
)
func main() {
// 1. fmt.Scanf:控制台解析“姓名 年龄”(需手动输入,如“sanmiao 20”)
var name string
var age int
fmt.Print("请输入姓名 年龄:")
successCount, err := fmt.Scanf("%s %d", &name, &age)
if err != nil {
fmt.Printf("解析失败:成功解析%d个值,错误:%v\n", successCount, err)
} else {
fmt.Printf("控制台解析结果:姓名=%s,年龄=%d\n", name, age)
}
// 2. fmt.Sscanf:解析固定格式日志字符串(修正变量名重复问题)
logStr := "2025-10-31 20:08:20 [ INFO ] 服务启动完成 (耗时30ms"
var logDate, logTime, level, msg string // 拆分日期和时间变量,避免覆盖
var cost int
// 格式字符串与logStr结构严格匹配(日期+时间+[级别]+消息+耗时)
_, _ = fmt.Sscanf(logStr, "%s %s [ %s ] %s (耗时%dms",
&logDate, &logTime, &level, &msg, &cost)
fmt.Printf("字符串解析结果:日期=%s,时间=%s,级别=%s,消息=%s,耗时=%dms\n",
logDate, logTime, level, msg, cost)
// 3. fmt.Fscan:从缓冲区解析配置数据
configBuf := bytes.NewBufferString("maxConn=100 timeout=30 retry=3")
var key1, key2, key3 string
var val1, val2, val3 int
_, _ = fmt.Fscan(configBuf, &key1, &val1, &key2, &val2, &key3, &val3)
fmt.Printf("缓冲区解析结果:%s=%d%s=%d%s=%d\n",
key1, val1, key2, val2, key3, val3)
}