问题描述
我有以下代码,该代码基本上将读取内容如下的文件奥克兰,汉密尔顿,罗托鲁瓦,惠灵顿0、125、235、660
125、0、110、535235、110、0、460660、535、460、0
I have a code as below which would basically read a file with contents which look likeAuckland,Hamilton,Rotorua,Wellington0, 125, 235, 660
125, 0, 110, 535235, 110, 0, 460660, 535, 460, 0
现在我要做的是将第一行分离出来并存储在一个字符数组中,然后从第二行到最后一行(基本上是矩阵)存储为二维整数数组,然后用逗号分隔.到目前为止,我已经用逗号分割了文件并将其存储到字符数组中,但是无法从数组中获取元素的数量(即城市数量).此外,我刚刚使用fgets来阅读第一行.还有其他有效的方法吗?谢谢.
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;
}
推荐答案
表达式
sizeof (arr1[j])
返回实际数组的大小,即MAXFLDSIZE
,而不是您放入数组的条目数.您必须使用变量来跟踪自己.
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.
这篇关于从存储在1D和2D数组中的文件中读取逗号分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!