Hispazn
Hispazn

Reputation: 103

Splitting string and storing into array (in C)

Trying to split the string of words that are scanned into my array "line" where new strings are split by a space and each split string is suppose to go into my array "scoops" so I can access any split string index for later

but I can't get it to work completely. When I tried printing the scoops array inside the while loop, for some reason the j index stayed 0 but is correctly printing the split strings.

When I try to see all the new strings outside the while loop, it only prints the first one of index 0. Crashes after that.

example input/output : enter image description here

(I tried searching similar posts and tried those solutions but still occurred same problem)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

    int i,c,j;
    char* order;
    char line[256]; //max order is 196 chars (19 quadruples + scoop)
    char* scoops[19]; //max 19 different strings from strtok

// get number of cases
    scanf("%d",&c);

// do number of cases
    for(i=0;i<c;i++){

        scanf("%s", &line);  //temp hold for long string of qualifiers
        order = strtok(line, " ");  //separate all the qualifiers 1 per line
        j = 0;
        while(order != NULL){

            scoops[j] = order;
            printf("scoops[%d] = %s\n",j,scoops[j]);
            order = strtok(NULL, " ");
            j++; 
        }

        // checking to see if array is being correctly stored
        //for(i=0;i<19;i++)
        //printf("scoops[%d] = %s\n",i,scoops[i]);

    }
return 0;
}

Upvotes: 2

Views: 1026

Answers (1)

R Sahu
R Sahu

Reputation: 206607

    scanf("%s", &line);  //temp hold for long string of qualifiers

does not read any whitespace characters. If you want to read a line of text, including whitespace characters, you'll need to use fgets.

    fgets(line, sizeof(line), stdin);

However, for this to work you'll need to add some code that ignores the rest of the line that's left in the input stream after the call to:

scanf("%d",&c);

Such as:

// Ignore the rest of the line.
char ic;
while ( (ic = getc(stdin)) != EOF && ic != '\n');

Upvotes: 1

Related Questions