pennyBoy
pennyBoy

Reputation: 397

Separating a string by space and storing it in an array of pointers

My program takes in a string and I break the string into words based on a space, I store the words in an array of pointers. However for some reason it is not separating the words into the appropriate index. In this example and the picture below the text "suspend 0", token1 should correspond to 0 however it corresponds to "end"

int main(){
    int ch ,n= 1;
    int i = 0;
    char str[512], *token[5], *act_token;
    while(1){

            printf("Enter text: ");
            while((ch = getchar()) != '\n')
                    str[i++] = ch;
            str[i] = '\0';
            i = 0;

            printf("string: %s\n", str);

            int spaces = 0;
            for(int counter  = 0; counter < strlen(str) + 1; counter++){
                    if(str[counter] == ' '){
                            spaces++;
                    }
            }
            printf("Spaces: %d\n", spaces);
            strtok(str, " ");
            while(n <= spaces && (act_token = strtok(NULL, " "))){
                    token[n] = act_token;
                    n++;

            }
            token[n] = NULL;
    //      printf("token[1]: %s\n", token[1]);
            for(int x = 1; x < spaces+1; x++){
                    printf("token[%d]: %s\n", x, token[x]);

            }
    }
    return 0;

}

Upvotes: 0

Views: 48

Answers (1)

Alex Lop.
Alex Lop.

Reputation: 6875

In this example and the picture below the text "suspend 0", token1 should correspond to 0 however it corresponds to "end"

That'a because (most likely) your index n, which is for some reason initiated to 1 (why not 0?) outside the while loop is not reset at the end of each while loop iteration...

Try this:

        while(n <= spaces && (act_token = strtok(NULL, " "))){
                token[n] = act_token;
                n++;

        }
        token[n] = NULL;
        n = 1; <-- *** add this line ***
//      printf("token[1]: %s\n", token[1]);
        for(int x = 1; x < spaces+1; x++){
                printf("token[%d]: %s\n", x, token[x]);

        }

NOTE1: You could eliminate all those search loops if you checked each char during the input process inside while((ch = getchar()) != '\n'). Anyway you collect the input char by char, so check it's value and count the spaces + split the words.

NOTE2: You are creating arrays of fixed size (for which is better to use defines) but you never check for the input not to exceed the limits of those arrays.

Upvotes: 1

Related Questions