问题
I have a code as below which would basically read a file with contents which look like
Auckland,Hamilton,Rotorua,Wellington
0, 125, 235, 660
125, 0, 110, 535
235, 110, 0, 460
660, 535, 460, 0
Now what I want to do is I want to separate out the first line and store it in a character array and from second line till the end(which is the matrix basically) into a 2dimensional integer array and ofcourse splitting by commas. So far I have split file by commas and have stored into characters array but not able to get the number of elements from the array(i.e number of cities). Moreover I have just used fgets to read the first line. Is there any other efficient way to do this? Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXFLDS 200
#define MAXFLDSIZE 32
void parse( char *record, char *delim, char arr[MAXFLDS][MAXFLDSIZE],int *fldcnt)
{
char*p=strtok(record,delim);
int fld=0,fld1=0;
while(p)
{
strcpy(arr[fld],p);
fld++;
p=strtok('\0',delim);
}
*fldcnt=fld;
}
int main(int argc, char *argv[])
{
char tmp[1024];
int fldcnt=0;
int j=0,k=0;
char arr[MAXFLDS][MAXFLDSIZE],arr1[MAXFLDS][MAXFLDSIZE];
int recordcnt=0;
FILE *in=fopen("C:\\Users\\Sharan\\Desktop\\cities.txt","r");
if(in==NULL)
{
perror("File open error");
exit(EXIT_FAILURE);
}
fgets(tmp,sizeof(tmp),in);
parse(tmp,",",arr1,&fldcnt);
k=sizeof(arr1)/sizeof(arr1[0]);
printf("arr size:%d",k);
for(j=0;j<fldcnt;j++)
{
printf("cities:%d\n",sizeof (arr1[j]));
}
while(fgets(tmp,sizeof(tmp),in)!=0)
{
int i=0,j=0;
recordcnt++;
parse(tmp,", ",arr,&fldcnt);
for(i=0;i<fldcnt;i++)
{
printf("%s\n",arr[i]);
}
}
fclose(in);
return 0;
}
回答1:
The expression
sizeof (arr1[j])
returns the size of the actual array, i.e. MAXFLDSIZE
, not the number of entries you put in it. You have to keep track of that yourself with variables.
来源:https://stackoverflow.com/questions/12505297/reading-comma-seperated-values-from-a-file-storing-in-a-1d-and-2d-array