1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How does strtok work in this case?

  1. Oct 11, 2015 #1
    1. The problem statement, all variables and given/known data
    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 doesnt detect if the first line has two values or not. If it does, then it should displayed an error.

    2. Relevant equations
    Code (Text):

    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 doesnt 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

    3. The attempt at a solution
     
    Last edited by a moderator: Oct 11, 2015
  2. jcsd
  3. Oct 11, 2015 #2

    Svein

    User Avatar
    Science Advisor

  4. Oct 11, 2015 #3
  5. Oct 11, 2015 #4

    Svein

    User Avatar
    Science Advisor

    Maybe because NULL is an invalid pointer (by definition).
     
  6. Oct 11, 2015 #5
    even the code in the website that you gave me doesnt work
    Code (Text):

    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);

     
     
  7. Oct 11, 2015 #6

    Svein

    User Avatar
    Science Advisor

    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";).
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: How does strtok work in this case?
Loading...