简体   繁体   中英

Printf is only printing the first word in a string?

I noticed that my variable input2 is only printing the first word in the string, which is leading to problems with the rest of the program (ie not printing the nouns correctly). Any insight on why this is occurring would be appreciated.

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

strtok() modifies the string you pass in as the source, so calling strtok() with argv[1] a second time doesn't act on the original value of argv[1] , but only the first token.

You might want to do something like:

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

and act on the string s o argv[1] will be left unchanged - you can process it again later. However, you'll need to free the duplicated string's memory when you're done with it.

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