I want to split a string into several strings stored in an array (of strings). I tried to use strtok_r, but I couldn't get that to work. So I tried doing it using this code:
int r=0;
int c=0;
for (int e=0;buf2[e]!=NULL;e++) {
if (buf2[e]!=",") {
monsters[i].types[c][r] = buf2[e];
r++;
} else {
r=0;
c++;
}
}
buf2 is the string I'm splitting, monsters[i].types[c] is the array of strings I'm splitting it into. When I do this, it gives me:
In file included from main.c:7:0:
resource.h: In function ‘main’:
resource.h:97:22: warning: comparison between pointer and integer [enabled by default]
for (int e=0;buf2[e]!=NULL;e++) {
^
resource.h:98:14: warning: comparison between pointer and integer [enabled by default]
if (buf2[e]!=",") {
^
I tried putting the ascii values instead of NULL & ",", and it didn't give me any warnings, but it didn't work. And is there any way to include the two extra variable declarations before the for into the for loop, next to the other int declaration?
Edit:
So I tried using strtok, this is my code:
buf3 = strtok(buf2,",");
strcpy(monsters[i].types[0],buf3);
for (int e=1;buf3!=NULL;e++) {
buf3 = strtok(NULL,",");
strcpy(monsters[i].types[e],buf3);
}
This gives me a Segmentation fault (core dumped)
ReEdit:
OK, so I just needed to switch the order of setting buf3 & the strcpy:
buf3 = strtok(buf2,",");
for (int e=0;buf3!=NULL;e++) {
strcpy(monsters[i].types[e],buf3);
buf3 = strtok(NULL,",");
}