在一段字符串处理时,使用sscanf函数出现问题:
#include <stdio.h>
#include <string.h>
int main(void)
{
int id = 0;
char str[32];
char mode[8];
char ip[32];
memset(mode, 0, sizeof(mode));
memset(ip, 0, sizeof(ip));
memset(str, 0, sizeof(str));
strcpy(str, "1,\"IP\",\"192.168.1.1\"");
/* 1,"IP","192.168.1.1" */
printf("str = %s\n", str);
/* \"%s\" */
sscanf(str, "%d,\"%s\",\"%s\"", &id, mode, ip);
/* id = 1, mode = IP","192.168.1.1", ip = 1.1" */
printf("id = %d, mode = %s, ip = %s\n", id, mode, ip);
return 0;
}
要解析的字符串为 1,"IP","192.168.1.1"
经过上述代码,结果比较奇怪,怀疑是\"%s\"这样的匹配形式有问题,因为虽然加了双引号转义,但是sscanf函数并没有安装预想结果来解析;
查了一下资料,找到了一种比较好的解决方法,我比较low,之前并没有用过通配符,这样学习了一下
修改后的代码为
#include <stdio.h>
#include <string.h>
int main(void)
{
int id = 0;
char str[32];
char mode[8];
char ip[32];
memset(mode, 0, sizeof(mode));
memset(ip, 0, sizeof(ip));
memset(str, 0, sizeof(str));
strcpy(str, "1,\"IP\",\"192.168.1.1\"");
/* 1,"IP","192.168.1.1" */
printf("str = %s\n", str);
/* \"%[^\"]\" */
sscanf(str, "%d,\"%[^\"]\",\"%[^\"]\"", &id, mode, ip);
/* id = 1, mode = IP, ip = 192.168.1.1 */
printf("id = %d, mode = %s, ip = %s\n", id, mode, ip);
return 0;
}
这样显示的结果就正确了。
原文:http://www.cnblogs.com/hancq/p/5014393.html