使用strtok存储数组

时间:2014-12-25 19:08:38

标签: c arrays runtime-error strtok

int main (){

FILE *file = fopen ( "C:\\input.txt", "r" );
int i=0, j=0, k=0;

char *result[10][10];   
char line[100];    
char *value;
char *res[100][100];

for(i=0; i<=9; i++){         
    for(j=0;j<=9;j++){
        result[i][j] = NULL;
    }
}

while(fgets(line, sizeof(line), file)){
    char *array=strtok(line,"\n");
    res[0][0]=strdup(array);  

    printf("\n\n\n %s RES \n",res[0][0]);
    array=strtok(array,"\n");
    res[0][1]=strdup(array);

    printf("\n\n\n %s RES \n",res[0][1]);
    array=strtok(line,"\n");
    res[0][2]=strdup(array);
}

我想逐行将数组存储在txt文件中。输入文件中有3行。我希望每一行都存储在一个数组中。我怎样才能做到这一点 ?这总是存储第一个元素。

我的输入文件:

George    :Math1,History2,Math2
ELizabeth :Math2,Germany1,spanish1
Adam      :Germany1,History2,Math1

1 个答案:

答案 0 :(得分:0)

为了将这三行读入数组,为什么不使用这么简单的东西:

 char res[100][100];
 int i =0;
 while(fgets(line, sizeof(line), file)){
        strcpy(&res[i][0],line);
        printf("%s \n",&res[i][0]);
        i++;
 }