1. Limited time only! Sign up for a free 30min personal 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!

Homework Help: TokenCounter of a string displaying not desirable results

  1. Oct 12, 2015 #1
    1. The problem statement, all variables and given/known data
    I am currently coding a program which reads a file and makes a graph based on the arrangement of the data in the file. The first line of the file stands for the number of vertices and the rest of the lines stand for the edges
    something like this:
    1 2
    2 3
    3 4
    In the first line when I add a second number such as 4, so the first line looks like 3 4, my parseN function is supposed to display an error saying the first line is wrong hence there should be just one number. To achieve this, I use a counterToken function which counts the number of tokens in the first line. When I add this second number, the program works fine displaying the error, but then when I delete this second number and leave the text cursor 2 spaces away from the string in this case "3", my counterToken function begins to count 2 tokens all the time in the first line.
    2. Relevant equations
    Code (Text):
    int ParseN(char line[])
        int verticesN;
        int NumberOfTokens=CountTokens(line);
                printf("bad firstline\n");

        char* pt=strtok(line," -");
        return verticesN;

    int CountTokens(char line[])
        char clone[sizeof(line)];

              const char s[2] = " -";
              char *token;
              int number=0;
              token = strtok(clone,s);
              while( token != NULL )
                 token = strtok(NULL,s);


              return number;

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


    User Avatar

    Staff: Mentor

    I think you're saying that if the first line contains a number with trailing spaces, your routine returns a count of two or more numbers?
  4. Oct 13, 2015 #3
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted