简体   繁体   English

c-strtok和while循环终止问题

[英]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. 基本上,每次遇到空白时,我试图将用户输入连接到char数组(源)的数组中。 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). 换句话说,如果sourceHold包含“祝您生日快乐”,则源的数组内容将为“ happy”(在0),“ birthday”(在1),“ to”(在2),“ you”(在3)。 sourcesTag holds the current index of the array of char arrays. sourcesTag保存char数组的当前索引。 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? 我一直在退出循环时出错(代码始终在完全退出循环之前会中断。最后的“ LOOP EXIT”打印行从不打印。在那里放置测试有什么问题。为什么我的循环不会终止?猜测这是因为在对整个输入字符串进行标记后,while语句未正确终止,但是什么是好的语句?

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 循环中的任何内容都不会更改sourceHold

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

makes sure that the break ing condition 确保break条件

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

is never met, since the strtok overwrites the '\\n' (if there is one at all) with a '\\0' . 永远不会遇到,因为strtok'\\0'覆盖'\\n' (如果有的话)。

So yes, you have an infinite loop, adding a check sourceHold[0] != 0 should fix that. 所以,是的,您有一个无限循环,添加一个check sourceHold[0] != 0应该可以解决该问题。

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")); 避免产生可疑的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. 首次调用strtok()时,应在str中指定要解析的字符串。 In each subsequent call that should parse the same string, str should be NULL. 在每个随后的应解析相同字符串的调用中,str应该为NULL。

You need to call it once with sourceHold and then all the other calls should be called with NULL. 您需要使用sourceHold调用一次,然后所有其他调用都应使用NULL进行调用。 Perhaps something like so: 也许像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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