How does strtok work in this case?

  • Thread starter Thread starter TheMathNoob
  • Start date Start date
  • Tags Tags
    Work
AI Thread Summary
The discussion revolves around a coding issue with the `strtok` function in C, specifically regarding its ability to detect a NULL value when parsing a line of input. The user is attempting to parse a line that indicates the number of vertices and edges for a graph but encounters problems when the first line contains only one value. There are suggestions to check the implementation of `strtok`, as it seems the code does not correctly identify when the second token is NULL. Additionally, there is a note about memory management, highlighting that the string should be defined with enough space for a null terminator. The conversation emphasizes the importance of correctly handling tokenization to avoid errors in the graph representation.
TheMathNoob
Messages
189
Reaction score
4

Homework Statement


I have a file which has data set in this way
1
2 3
4 7
1 2
I have to make a graph with those values considering that the value of the first line corresponds to the vertices and the next two values per line to the edges. I am having troubles with a function that doesn't detect if the first line has two values or not. If it does, then it should displayed an error.

Homework Equations

[/b]
Code:
int ParseN(char line[])
{
    char* first;
    char* second;
    int true=1;
    int numberVertices=0;
    char* pt=strtok(line," -");
    printf("%s",pt);
    char* pt2=strtok(NULL," -");
    printf("%s",pt2);
    if(pt2==NULL) // in this case when I test my file with just one value in the first line, it doesn't detect the NULL
    {
        puts("yes");
    }
    else
        puts("no");
    return 1;
}

by the way sorry for not following the directions in the previous post. Now I understand what I have to do

The Attempt at a Solution

 
Last edited by a moderator:
Physics news on Phys.org
TheMathNoob said:
My code is not detecting the null
Maybe because NULL is an invalid pointer (by definition).
 
Svein said:
Maybe because NULL is an invalid pointer (by definition).
even the code in the website that you gave me doesn't work
Code:
char str[5]="jk kj";
    char s=" ";
    char* token;
    int counter=0;
    token = strtok(str,s);

      while( token != NULL )
      {
         printf( " %s\n", token );
         token = strtok(NULL,s);
      }    free(str);
 
A slight error: Your first line (char str[5]="jk kj";) has no room for a string terminator. You should use char *str="jk kj"; (or char str[]="jk kj";).
 
Back
Top