拆分字符串并存储到数组中(在 C 中)

Splitting string and storing into array (in C)

尝试将扫描到的单词字符串拆分到我的数组 "line" 中,新字符串被 space 拆分,每个拆分字符串都应该进入我的数组 "scoops" 这样我以后就可以访问任何拆分字符串索引

但我无法让它完全工作。当我尝试在 while 循环内打印 scoops 数组时,由于某种原因,j 索引保持为 0,但正确打印了拆分字符串。

当我试图在 while 循环之外查看所有新字符串时,它只打印索引 0 的第一个字符串。之后崩溃。

示例input/output:

(我尝试搜索类似的帖子并尝试了这些解决方案,但仍然出现同样的问题)

#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;
}
    scanf("%s", &line);  //temp hold for long string of qualifiers

不读取任何空白字符。如果你想阅读一行文本,包括空白字符,你需要使用 fgets.

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

但是,要使其正常工作,您需要添加一些代码来忽略调用后输入流中剩余的行:

scanf("%d",&c);

如:

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