Printf只打印字符串中的第一个单词?

时间:2013-05-29 18:37:06

标签: c arrays printf binary-search

我注意到我的变量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;
}

1 个答案:

答案 0 :(得分:6)

strtok()修改您传入的字符串作为来源,因此第二次使用strtok()调用argv[1]不会对原始值argv[1]起作用,但只有第一个令牌。

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

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

并对字符串s进行操作o argv[1]将保持不变 - 您可以稍后再次处理它。但是,当你完成它时,你需要释放重复的字符串的内存。