sscanf详解
2025/9/8大约 3 分钟
sscanf()
sscanf() 用于从字符串中解析数据,和 scanf() 类似,但 sscanf() 是从字符串读取,而不是从标准输入读取。
🔹 基本用法
📌 语法
int sscanf(const char *str, const char *format, ...);str:要解析的字符串。format:格式化字符串,类似scanf()的格式。...:存放解析结果的变量的地址。
返回值:
- 成功解析的变量个数。
- 解析失败返回
0或EOF。
🔹 示例
✅ 解析整数和浮点数
#include <stdio.h>
int main() {
char input[] = "123 45.67";
int a;
float b;
sscanf(input, "%d %f", &a, &b);
printf("a = %d, b = %.2f\n", a, b);
return 0;
}输出:
a = 123, b = 45.67解析流程:
"%d"解析123,存入a。"%f"解析45.67,存入b。
🔹 解析字符串
✅ 解析多个字符串
#include <stdio.h>
int main() {
char input[] = "Hello World";
char str1[10], str2[10];
sscanf(input, "%s %s", str1, str2);
printf("str1 = %s, str2 = %s\n", str1, str2);
return 0;
}输出:
str1 = Hello, str2 = World🔹 解析混合数据
✅ 提取姓名、年龄、身高
#include <stdio.h>
int main() {
char input[] = "Tom 25 1.75";
char name[20];
int age;
float height;
sscanf(input, "%s %d %f", name, &age, &height);
printf("Name: %s, Age: %d, Height: %.2f\n", name, age, height);
return 0;
}输出:
Name: Tom, Age: 25, Height: 1.75🔹 解析带格式的字符串
✅ 解析日期
#include <stdio.h>
int main() {
char input[] = "2025-03-10";
int year, month, day;
sscanf(input, "%d-%d-%d", &year, &month, &day);
printf("Year: %d, Month: %d, Day: %d\n", year, month, day);
return 0;
}输出:
Year: 2025, Month: 3, Day: 10🔹 解析部分数据
✅ 只解析前两个数
#include <stdio.h>
int main() {
char input[] = "100 200 300";
int x, y;
sscanf(input, "%d %d", &x, &y); // 只解析前两个数
printf("x = %d, y = %d\n", x, y);
return 0;
}输出:
x = 100, y = 200剩下的 300 被忽略。
🔹 过滤无关字符
✅ 解析带单位的数值
#include <stdio.h>
int main() {
char input[] = "Temperature: 25C";
int temp;
sscanf(input, "Temperature: %dC", &temp);
printf("Temperature = %d°C\n", temp);
return 0;
}输出:
Temperature = 25°C💡 技巧: sscanf() 可以直接跳过特定字符(如 Temperature: 和 C),只提取数值。
🔹 sscanf() 返回值
✅ 检查解析是否成功
#include <stdio.h>
int main() {
char input[] = "50 kg";
int weight;
char unit[10];
int result = sscanf(input, "%d %s", &weight, unit);
if (result == 2) {
printf("Weight: %d %s\n", weight, unit);
} else {
printf("Parsing failed!\n");
}
return 0;
}输出:
Weight: 50 kg✅ 解析成功返回 2(成功解析了两个变量)。
🔹 sscanf() vs scanf()
| 功能 | sscanf() | scanf() |
|---|---|---|
| 输入源 | 字符串 | 标准输入(键盘) |
| 适用场景 | 处理缓冲区数据、日志解析、协议解析等 | 读取用户输入 |
| 常用格式 | "%d %f %s" | "%d %f %s" |
| 解析失败 | 返回 0 或 EOF | 阻塞等待输入 |
🔹 总结
✅ sscanf() 用于从字符串解析数据,常用于日志、文件数据处理。
✅ 支持整数、浮点数、字符串,可以跳过固定字符。
✅ 返回成功解析的变量个数,可以用 if 判断是否成功。
✅ 比 scanf() 更安全,不会等待输入,更适合处理已有数据。 🚀
sscanf(str, "pitch:%.1f roll:%.1f", &rec_pitch, &rec_roll); // ❌ 错误%.1f 这样的写法是用在 printf 里的,表示“输出时保留 1 位小数”,是输出格式化,不是输入格式化。

