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

user1768079 Source

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 open
    fin.getline(line, 40, '\n');
    cout << line << endl;
    ptr = strtok (line, " ");

    while(ptr != NULL)
          sprintf(firstname, "%s", ptr);
          sprintf(lastname, "%s", ptr);
          sprintf(id, "%s", ptr);
          sprintf(grade1, "%s", ptr);
          sprintf(grade2, "%s", ptr);
          sprintf(grade3, "%s", ptr);
          sprintf(grade4, "%s", ptr);
          sprintf(grade5, "%s", ptr);
          sprintf(grade6, "%s", ptr);
        ptr = strtok (NULL, " ");
        if(ptr == NULL)


answered 5 years ago Some programmer dude #1

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

answered 5 years ago qPCR4vir #2

As @Joachim Pileborg the principal problem is reset c. It could be more explicit to initialize it before enter the inner loop c=0; and to add and else for each if except for the last.

comments powered by Disqus