基本语法
int sscanf(const char *str, const char *format, ...);
str
:要解析的源字符串;
format
:格式控制字符串;
...
:用于保存解析结果的变量地址;
返回值:成功读取并赋值的字段数量。
常见用法及示例
1.基本类型的读取
#include <stdio.h>
int main() {
const char *str = "42 3.14 A";
int i;
float f;
char c;
sscanf(str, "%d %f %c", &i, &f, &c);
printf("int: %d, float: %.2f, char: %c\n", i, f, c);
return 0;
}
输出:
int: 42, float: 3.14, char: A
2.字符串的读取
#include <stdio.h>
int main() {
const char *str = "Hello World";
char word1[10], word2[10];
sscanf(str, "%s %s", word1, word2);
printf("First word: %s, Second word: %s\n", word1, word2);
return 0;
}
注意:%s
读取遇到空白符会停止(空格、换行、Tab)。
输出:
First word: Hello, Second word: World
3.限制字符串长度
char str[] = "abcdef";
char buf[4];
sscanf(str, "%3s", buf); // 最多读取3个字符 + 末尾自动加\0
printf("buf: %s\n", buf); // 输出:abc
输出:
buf: abc
4.解析日期格式字符串
#include <stdio.h>
int main() {
const char *date = "2025-04-08";
int year, month, day;
sscanf(date, "%d-%d-%d", &year, &month, &day);
printf("Year: %d, Month: %d, Day: %d\n", year, month, day);
return 0;
}
输出:
Year: 2025, Month: 4, Day: 8
5.跳过字段(使用*)
#include <stdio.h>
int main() {
const char *str = "Name: John Age: 25";
int age;
sscanf(str, "Name: %*s Age: %d", &age); // 忽略名字
printf("Age: %d\n", age);
return 0;
}
输出:
Age: 25
6.读取包含空格的整行(scanset %[^\n]
)
#include <stdio.h>
int main() {
const char *str = "Title: The Great Gatsby";
char title[50];
sscanf(str, "Title: %[^\n]", title);
printf("Book title: %s\n", title);
return 0;
}
输出:
Book title: The Great Gatsby
7.解析进制和科学计数法
#include <stdio.h>
int main() {
const char *str = "0xFF 077 3.14e2";
int hex, oct;
float sci;
sscanf(str, "%x %o %e", &hex, &oct, &sci);
printf("Hex: %d, Oct: %d, Sci: %.2f\n", hex, oct, sci);
return 0;
}
输出:
Hex: 255, Oct: 63, Sci: 314.00
8.用返回值判断解析成功的字段数量
#include <stdio.h>
int main() {
const char *str = "123 abc";
int num;
char word[10];
int ret = sscanf(str, "%d %s", &num, word);
if (ret == 2) {
printf("Parsed: %d and %s\n", num, word);
} else {
printf("Parsing failed, only %d items matched.\n", ret);
}
return 0;
}
输出:
Parsed: 123 and abc
使用注意事项总结
注意点 |
说明 |
%s 默认不读取空格 |
如果要读取带空格的字符串,用 %[^\n] 或 %[^\t] |
注意缓冲区溢出 |
为 %s 提供的数组必须足够大或限制读取长度 |
返回值用于验证匹配字段 |
推荐使用 sscanf 的返回值判断解析是否成功 |
类型匹配必须准确 |
%f 对应 float ,%lf 对应 double |
忽略字段用 * |
可以省略不需要保存的字段 |
%n 可用于获取当前位置 |
返回已读取的字符数,用于更复杂的拆分 |