separating string between commas into an array in c -
i want split string several strings stored in array (of strings). tried use strtok_r
, couldn't work. tried doing using code:
int r=0; int c=0; (int e=0;buf2[e]!=null;e++) { if (buf2[e]!=",") { monsters[i].types[c][r] = buf2[e]; r++; } else { r=0; c++; } }
buf2
string i'm splitting, monsters[i].types[c]
array of strings i'm splitting into. when this, gives me:
in file included main.c:7:0: resource.h: in function ‘main’: resource.h:97:22: warning: comparison between pointer , integer [enabled default] (int e=0;buf2[e]!=null;e++) { ^ resource.h:98:14: warning: comparison between pointer , integer [enabled default] if (buf2[e]!=",") { ^
i tried putting ascii values instead of null
& ","
, , didn't give me warnings, didn't work. , there way include 2 variable declarations before for
loop, next other int declaration?
edit:
so tried using strtok
, code:
buf3 = strtok(buf2,","); strcpy(monsters[i].types[0],buf3); (int e=1;buf3!=null;e++) { buf3 = strtok(null,","); strcpy(monsters[i].types[e],buf3); }
this gives me segmentation fault (core dumped)
reedit:
ok, needed switch order of setting buf3
& strcpy
:
buf3 = strtok(buf2,","); (int e=0;buf3!=null;e++) { strcpy(monsters[i].types[e],buf3); buf3 = strtok(null,","); }
firstly, character constant syntax in c language uses single quotation marks: ','
, not ","
.
secondly, don't compare character values null
. null
reserved pointer contexts. terminating 0 character can described '\0'
or 0
.
thirdly, there dedicated library functions designed simplify task, strtok
. don't know though whether can use them.
as variable declarations, yes, can put them in for
long have same type
for (int e = 0, r = 0, c = 0; ...
note though variables declared in way not available after for
. , need c
after for
.
Comments
Post a Comment