0

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 
}
nicu98
  • 13
  • 3
  • 2
    Explain that loop to your [rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging), particularly in consideration of what `strtok` returns when it *fails*, and what you do between the time that fail happens and the next check of the while-condition. – WhozCraig Aug 11 '22 at 17:01

2 Answers2

0

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 
  }
}
Ian Abbott
  • 15,083
  • 19
  • 33
0

strtok() is not as difficult to use as all that.

int main( void ) {
    char str[] = "The quick brown fox jumps over the lazy dog";
    char *sepChars = " ";

    int i = 0;
    for( char *pTok = str; ( pTok = strtok( pTok, sepChars ) ) != NULL; pTok = NULL )
        printf( "Token #%d: '%s'\n", i++, pTok );

    return 0;
}

Output

Token #0: 'The'
Token #1: 'quick'
Token #2: 'brown'
Token #3: 'fox'
Token #4: 'jumps'
Token #5: 'over'
Token #6: 'the'
Token #7: 'lazy'
Token #8: 'dog'
Fe2O3
  • 6,077
  • 2
  • 4
  • 20