sscanf的高级使用

来源:互联网 发布:python anaconda 安装 编辑:程序博客网 时间:2024/06/07 22:28
最近为了使用正则表达式配合sscanf使用,处理:
char buf[]="123$$asdfasd$$eeeffff$$liman$$1111111111111$$ccdddd$$hello"; 上面的字符串分割开来。
需要的结果如下:
sscanf(buf, "%[^$]$$%[^$]$$%[^$]$$%[^$]$$%[^$]$$%[^$]$$%[^$]", user, host, test1, msg, test2, test3, test4);


^表示"非",[^\n]表示读入换行字符就结束读入。这个是scanf的正则用法,我们都知道scanf不能接收空格符,但是使用%[^\n]就可以了。
*表示该输入项读入后不赋予任何变量,即scanf("%*[^\n]%*c")表示跳过一行字符串

如果需要取后面几个开始呢:
(3) * 表示跳过,如:
int main()
{
 char buf[100]="123:asdfasd:2342342:liman:host:34234:hello";
 char user[20]="";
 char host[20]="";
 char msg[20]="";
 int cmd = 0; 
 sscanf(buf, "%*d:%*[^:]:%*[^:]:%[^:]:%[^:]:%d:%s", user, host, &cmd, msg);
 return 0;
}
结果:user="liman",host="host",cmd=34234,msg=hello



参考sscanf的链接:
1->http://blog.chinaunix.net/uid-26284412-id-3189214.html
2->http://blog.csdn.net/sheji105/article/details/53726792
0 0
原创粉丝点击