简体   繁体   中英

c - strtok and a while loop termination issue

basically im trying to concatenate a user input into an array of char arrays (sources) each time a whitespace is encountered. in other words, if sourceHold contains "happy birthday to you", the array contents of sources will be "happy" (at 0), "birthday" (at 1), "to" (at 2), "you" (at 3). sourcesTag holds the current index of the array of char arrays. I keep getting errors with exiting the loop (the code always breaks before it can exit the loop completely. that last "LOOP EXIT" print line never prints. placed that there to test what was wrong. any idea why my loop wont terminate? im guessing that this is because the while statement doesn't properly terminate when the whole input string has been tokenized, but what would be a good statement?

while(sourceHold != NULL)
    {
        if(sourceHold[0] == '\n')
            break;

        printf("%s \n", sourceHold);

        strcpy(sources[sourcesTag], strtok(sourceHold, " "));
        sourcesTag++;

        strcpy( sourceHold, strtok(NULL, "\n"));
    } 
    printf("LOOP EXIT");
while(sourceHold != NULL)

Nothing in the loop ever changes sourceHold , and the

strcpy( sourceHold, strtok(NULL, "\n"));

makes sure that the break ing condition

if(sourceHold[0] == '\n')

is never met, since the strtok overwrites the '\\n' (if there is one at all) with a '\\0' .

So yes, you have an infinite loop, adding a check sourceHold[0] != 0 should fix that.

It would be better, however, to have a pointer

char *tok = strtok(sourceHold, " ");
while(tok != NULL) {
    strcpy(sources[sourcesTag++], tok);
    tok = strtok(NULL, " \n");
}

to avoid the dubious strcpy(sourceHold, strtok(NULL, "\\n")); .

Take a look at the man page .

On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

You need to call it once with sourceHold and then all the other calls should be called with NULL. Perhaps something like so:

    strcpy(sources[sourcesTag], 
           strtok(0 == sourcesTag ? sourceHoldPtr : NULL, " "));
    sourcesTag++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM