#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *str="[03:39.68][02:39.34][01:10.71]爱能不能永远单纯没有悲哀";
char *time_buf[5]={NULL};
static int i=0,j;
char s[200]="";
while(*str=='[')
{
sscanf(str,"[%[^]]",s);
// printf("%s\n",s);
time_buf[i]=s;
i++;
str=str+10;
}
for(j=0;j<i;j++)
{
puts(time_buf[j]);
}
printf("str=%s\n",str);
return 0;
}
你这句不对time_buf[i]=s;
你这样表示time_buf的每个元素都指向了s(相当于前3个元素指向的是同一个s,楼主打印地址就能验证)
后面调用的sscanf(str,"[%[^]]",s);会影响到前面的,所以打印出来的都是最后的01:10.71
要为每个元素都分配不同的空间才行
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *str = "[03:39.68][02:39.34][01:10.71]爱能不能永远单纯没有悲哀";
char *time_buf[5] = { NULL };
static int i = 0, j;
char s[200] = "";
while (*str == '[')
{
sscanf(str, "[%[^]]", s);
// printf("%s\n",s);
time_buf[i] = (char *)malloc(sizeof(char) * 200);
strcpy(time_buf[i], s);
i++;
str = str + 10;
}
for (j = 0; j<i; j++)
{
puts(time_buf[j]);
}
printf("str=%s\n", str);
return 0;
}