头文件:#include <stdio.h>
sscanf()函数用于从字符串中读取指定格式的数据, 其原型如下:
int sscanf (char *str, char * format [, argument, ...]);
[参数] 参数 str 为要读取数据的字符串; format 为用户指定的格式; argument 为变量, 用来保存读取到的数据.
[返回值] 成功则返回参数数目, 失败则返回 - 1, 错误原因存于 errno 中.
sscanf()会将参数 str 的字符串根据参数 format(格式化字符串)来转换并格式化数据(格式化字符串请参考 scanf()), 转换后的结果存于对应的变量中.
sscanf()与 scanf()类似, 都是用于输入的, 只是 scanf()以键盘 (stdin) 为输入源, sscanf()以固定字符串为输入源.
常用参数格式:%d,int; %f,float; %lf,double
[实例] 从指定的字符串中读取整数和小写字母.
- #include <stdio.h>
- int main(void)
- {
- char str
- [
- 100] ="123568qwerSDDAE";
- char lowercase[100];
- int num;
- sscanf
- (str
- ,
- "%d %[a-z]", &num, lowercase);
- printf
- (
- "The number is: %d.\n", num);
- printf("The lowercase is: %s.", lowercase);
- return 0;
- }
输出结果:
The number is: 123568.
The lowercase is: qwer.
可以看到 format 参数有些类似正则表达式(当然没有正则表达式强大, 复杂字符串建议使用正则表达式处理), 支持集合操作, 例如:
%[a-z] 表示匹配 a 到 z 中任意字符, 贪婪性(尽可能多的匹配)
%[aB'] 匹配 a,B,'中一员, 贪婪性
%[^a] 匹配非 a 的任意字符, 贪婪性
另外, format 不仅可以用空格界定字符串, 还可以用其他字符界定, 可以实现简单的字符串分割(更加灵活的字符串分割请使用 strtok() http://c.biancheng.net/cpp/html/175.html ). 例如:
- sscanf("2006:03:18", "%d:%d:%d", a, b, c);
- sscanf("2006:03:18 - 2006:04:18", "%s - %s", sztime1, sztime2);
[转载]sscanf 函数
来源: http://www.bubuko.com/infodetail-3043015.html