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

Time:08-12

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 
}

CodePudding user response:

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 
  }
}

CodePudding user response:

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'
  • Related