Search code examples
cstringtreeviewdelimiterstrtok

strtok() while loop is returning extra blank/place holder and not specified string


I have a path to some folders as a string and using strtok() to break down subfolders separated by , delimiter. Issue is when its printing in a TreeControl view (runs successfully) but its printing an extra blank folder (dotted/line space) for what looks like a future folder maybe? how do I get rid of that blank folder and only show the 2 folders (Pop, Country). I tried adding picture but not working so here is what it looks like on the treeview:

->/Desktop/Songs
  ->.....      this is where the blank is being inserted
  ->Pop
  ->Country 

Code:

HTREEITEM hItem;
HTREEITEM hsubItem;

char line[] = "/Desktop/Songs,Pop,Country" ;   
char* dir= strtok(line,",");    
printf("%s\n", dir);
hItem= treeview.InsertItem(dir); //add to a tree control as the root path or directory

while (dir!= NULL)
{
  dir= strtok(NULL,",");
  printf("%s\n", dir);
  hsubItem = treeview.InsertItem(dir, hItem); //add Pop Country below the first item 
}

Solution

  • When dir = strtok(NULL,","); is NULL the code is doing the same thing as when dir is not NULL.

    Fix it by checking dir is not NULL after the call to strtok inside the loop, and only treat dir as valid if it is not NULL. For example:

    while (dir!= NULL)
    {
      dir= strtok(NULL,",");
      if (dir != NULL)
      {
        printf("%s\n", dir);
        hsubItem = treeview.InsertItem(dir, hItem); //add Pop Country below the first item 
      }
    }
    

    The above code can be optimized to only test dir once per iteration:

    if (dir!= NULL)
    {
      while (1)
      {
        dir= strtok(NULL,",");
        if (dir == NULL)
        {
          break;
        }
        printf("%s\n", dir);
        hsubItem = treeview.InsertItem(dir, hItem); //add Pop Country below the first item 
      }
    }