-
strtok again
ok I am trying to read in from a file using fgets
the first part of the file looks like this
diagram,Human Circulatory System
:
: blah blah blah
: blah blah blah
:
vertex,1,brain
I don't need to save the part that says blah blah blah
I have put something in my code to skip over the lines that start with a colon but whenever I try to start reading again, there is a problem where I have indicated
I assume it is because strtok can't use NULL as a starting point because those lines were skipped over.
I am trying to read in the first line after the comments up to the comma. Once I have read that in I will proceed conditionally, based on what the string is.
So after I have read in the graph type and title, the next thing to read will be vertex, and then proceed based on the vertex conditions
Code:
while (fgets(line,100,readfile) != NULL)
{
strcpy(Graph->type, strtok(line,","));
strcpy(Graph->title, strtok(NULL,"\n"));
if(line[0] != ':')//if line isn't a comment
{
strcpy(info, strtok(NULL,","));//problem is here
if(strcmp(info, vertex) == 0)
{
strcpy(temp, strtok(NULL,","));
vertex_ptr->inumber = atoi(temp);
strcpy(vertex_ptr->city, strtok(NULL,"\n"));
}
if(strcmp(info, edge) == 0)
{
strcpy(temp, strtok(NULL,","));
edge_ptr->iedge_number = atoi(temp);
strcpy(temp, strtok(NULL,","));
edge_ptr->ideparture = atoi(temp);
strcpy(temp, strtok(NULL,","));
edge_ptr->idestination = atoi(temp);
strcpy(temp, strtok(NULL," "));
edge_ptr->edge_weight = atof(temp);
}
}
}
can anyone see how I can fix this?
-
strcpy(Graph->type, strtok(line,","));
strcpy(Graph->title, strtok(NULL,"\n"));
These appear inside your while loop, yet they only apply to the first line of the file
So I would perhaps
Code:
fgets(line,100,readfile);
strcpy(Graph->type, strtok(line,","));
strcpy(Graph->title, strtok(NULL,"\n"));
while (fgets(line,100,readfile) != NULL) {
...
-
Re: strtok again
I'd also add:
Code:
while (fgets(line,100,readfile) != NULL)
{
if (line[0] != ':')
{
strcpy(Graph->type, strtok(line,","));
...
and just take care of the colon directly. Why go thru all that strtok() stuff on a comment line?