Search code examples
c++ccstringstrtokarrays

splicing cstrings with strtok, only works on first execution of loop


I am trying to use strtok to splice a line read into a cstring into individual strings. Yes I know this could be done much more easily with string objects, but I'm not allowed to use them. When this code executes it works perfectly on the first line, then it continues to only work on that same line for every iteration of the loop. The file is being successfully read into the 'line' char array veriable, as evidenced by cout << line << endl; However strtok and the second while loop continue to split the first line read in every single time. Each line contains a first_name last_name ID and six grades. I guess I will just rewrite it and have getline delimit at white space and read in individual strings, but does anyone know why strtok is only splicing the first string on each successive iteration of the loop?

this is a code segment, assume all variables are correctly declared elsewhere

 while(!fin.eof())
    {//while open
    fin.getline(line, 40, '\n');
    cout << line << endl;
    ptr = strtok (line, " ");

    while(ptr != NULL)
        {
        if(c==0)
          sprintf(firstname, "%s", ptr);
        if(c==1)
          sprintf(lastname, "%s", ptr);
        if(c==2)
          sprintf(id, "%s", ptr);
        if(c==3)
          sprintf(grade1, "%s", ptr);
        if(c==4)
          sprintf(grade2, "%s", ptr);
        if(c==5)
          sprintf(grade3, "%s", ptr);
        if(c==6)
          sprintf(grade4, "%s", ptr);
        if(c==7)
          sprintf(grade5, "%s", ptr);
        if(c==8)
          sprintf(grade6, "%s", ptr);
        ptr = strtok (NULL, " ");
        if(ptr == NULL)
          break;
        c++;
        }
}

Solution

  • You do not reset the variable c after leaving the inner loop.