reading a line, tokenizing and assigning to struct in C
Posted
by
Dervin Thunk
on Stack Overflow
See other posts from Stack Overflow
or by Dervin Thunk
Published on 2010-12-21T19:49:37Z
Indexed on
2010/12/21
19:54 UTC
Read the original article
Hit count: 217
line
is fgets'd, and running in a while
loop with counter n
, d
is a struct with 2 char arrays, p
and q
. Basically, in a few words, I want to read a line, separate it into 2 strings, one up until the first space, and the rest of the line. I clean up afterwards (\n
from the file becomes \'0'). The code works, but is there a more idiomatic way to do this? What errors am I running into "unknowingly"?
int spc = strcspn(line," ");
strncpy(d[n].p, line, spc);
d[n].p[spc+1]='\0';
int l = strlen(line)-spc;
strncpy(d[n].q, line+spc+1, l);
char* nl = strchr(d[n].q, '\n');
if(nl){
*nl='\0';
}
n++;
Thanks.
© Stack Overflow or respective owner