0

我注意到我的变量 input2 只打印字符串中的第一个单词,这导致程序的其余部分出现问题(即未正确打印名词)。任何有关为什么会发生这种情况的见解将不胜感激。

int main(int argc, char* argv[]){

    char *input = strtok(argv[1], " \"\n");
    //printf("%s\n", input);
    int position;
    int check = 0;
    int first = 1;
    while (input != NULL) {
        position = binary_search(verbs, VERBS, input);
        //printf("%s\n", input);
        //printf("%d\n", position);
        if (position != -1){
            if (first){
                printf("The verbs were:");
                first = 0;
                check = 1;
            }
            printf(" %s", input);
        }
        input = strtok(NULL, " ");
    }
    if (check == 1){
        printf(".\n");
    }
    if (check == 0){
        printf("There were no verbs!\n");
    }

    char *input2 = strtok(argv[1], " \"\n");
    //printf("%s\n", input2);
    int position2;
    int check2 = 0;
    int first2 = 1;

    while (input2 != NULL) {
        position2 = binary_search(nouns, NOUNS, input2);
        //printf("%s\n", input2);
        //printf("%d\n", position2);
        if (position2 != -1){
            if (first2){
                printf("The nouns were:");
                first2 = 0;
                check2 = 1;
            }
            printf(" %s", input2);
        }
        input2 = strtok(NULL, " ");
    }
    if (check2 == 1){
        printf(".\n");
    }
    if (check2 == 0){
        printf("There were no nouns!\n");
    }

        return 0;
}
4

1 回答 1

6

strtok()修改您作为源传入的字符串,因此第二次调用不会作用于 的原始值strtok(),而只会作用于第一个标记。argv[1]argv[1]

您可能想要执行以下操作:

char* s = strdup(argv[1]);

并作用于字符串soargv[1]将保持不变 - 您可以稍后再次处理它。但是,您需要在完成后释放重复字符串的内存。

于 2013-05-29T18:39:42.260 回答