Store an array using strtok

ⅰ亾dé卋堺 提交于 2019-12-12 01:54:39

问题


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);
}

I want to store an array in a txt file line by line. There are 3 rows in my input file. I want every line is stored by in an array. How can I do that ? this is always store first element.

my input file :

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

回答1:


For reading those three lines into array why don't you use something as simple as this:

 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++;
 }


来源:https://stackoverflow.com/questions/27649985/store-an-array-using-strtok

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!