目录
一、描述
sscanf通常被用来解析并转换字符串,其格式定义灵活多变,可以实现很强大的字符串解析功能。
sscanf的原型
#include <stdio.h>
int sscanf(const char *str, const char *format, ...);
str:待解析的字符串;
format:字符串格式描述;
其后是一序列数目不定的指针参数,存储解析后的数据。
二、示例用法
1.sscanf的基本用法
整形数转换
int year, month, day;
int converted = sscanf("20221103", "%04d%02d%02d", &year, &month, &day);
printf("converted=%d, year=%d, month=%d, day=%d\n", converted, year, month, day);输出结果:
converted=3, year=2022, month=11, day=03
浮点型数转换
double longitude, latitude;
int converted = sscanf("113.123456789 31.123456789", "%lf %lf", &longitude, &latitude);
printf("converted=%d, longitude=%.9lf, latitude=%lf\n", converted, longitude, latitude);输出结果:
converted=2, longitude=113.123456789, latitude=31.123457
2.sscanf的高级用法
数字+字符串
char str[32] = "";
sscanf("123456abcdedf", "%31[0-9]", str);
printf("str=%s\n", str);输出结果:
str=123456
上面的格式中,[0-9]表示这是一个仅包含0-9这几个字符的字符串,前面使用数字31修饰词表示这个字符串缓冲区的最大长度(这也是sscanf最为人诟病的地方,很容易出现缓冲区溢出错误,实际上sscanf是可以避免出现缓冲区溢出的,只要在书写任何字符串解析的格式时,注意加上其缓冲区尺寸的限制)。
char str[32] = "";
sscanf("123456abcdedf", "%31[0-9a-z]", str);
printf("str=%s\n", str);
输出结果:
str=123456abcdedf
使用"^"的示例
在[]中增加^表示相反的意思
char str[32] = "";
sscanf("123456abcdedf", "%31[^a-z]", str);
printf("str=%s\n", str);输出结果:
str=123456
如上面的[a-z]表示一个不包含任何a-z之间的字符串,同时读取到'a'字符时停止。
使用"*"的示例
加上*修饰表示一个被忽略的数据,同时也不需要为它准备空间存放解析结果。
char str[32] = "";
int ret = sscanf("123456abcdedf", "%*[0-9]%31[a-z]", str);
printf("ret=%d, str=%s\n",ret, str);输出结果:
ret=1, str=abcdedf
如上面的例子中,我们就只使用了str一个参数存放%31[a-z]的解析结果,而sscanf也只返回1,表示只解析了一个数据。
使用特定字符串分割的示例
char test_buf[128] = "abc:1234";
char str[128] = {0};
int value = 0;
sscanf(test_buf, "abc:%s", str);
sscanf(test_buf, "abc:%d", value);
printf("str: %s \n", str);
printf("value=%d \n", value);
输出结果:
str:1234
value=1234