2

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;
}
2
  • 1
    Example input and expected output? Commented Feb 23, 2016 at 3:27
  • sorry, posted. The 4 is irrelevant. just an arbitrary number for now. But there is example string and it being split but unable to store it in different index Commented Feb 23, 2016 at 4:11

1 Answer 1

1
    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');
Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure how to incorporate the code to ignore the rest of the line
@Hispazn, just add those two lines after the call to scanf.
It says " error: too few arguments in to function 'getc' "
@Hispazn, my bad. I forgot to add stdin in the call to getc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.