title: Using strtok/strtok_r in a while loop in C++
body: <p>I'm getting unexpected behavior from the strtok and strtrok_r functions:</p>
  
  <pre><code>queue&lt;string&gt; tks;
  char line[1024];
  char *savePtr = 0;
  
  while(true)
  {
      //get input from user store in line
  
      tks.push(strtok_r(line, " \n", &amp;savePtr));  //initial push only works right during first loop
  
      char *p = nullptr;
      for (...)
      {
          p = strtok_r(NULL, " \n", &amp;savePtr);
          if (p == NULL)
          {
              break;
          }
          tks.push(p);
      }
      delete p;
      savePtr = NULL;
  
      //do stuff, clear out tks before looping again
  
  }
  </code></pre>
  
  <p>I've tried using <code>strtok</code> and realized that during the second loop, the initial push is not occurring.  I attempted to use the reentrant version <code>strtok_r</code> in order to control what the saved pointer is pointing to during the second loop by making sure it is null before looping again.</p>
  
  <p><code>tks</code> is only correctly populated during the first time through the loop - subsequent loops give varying results depending on the length of <code>line</code></p>
  
  <p>What am I missing here?</p>