【发布时间】:2013-12-21 14:04:13
【问题描述】:
我正在编写程序来计算分数。
输入文件full list.txt 看起来像:
123456,11,24,,51,,12,,76,,,531,12,,,,24,56,,,,,118,,,,,,,,,,,,,,20,,,,,
123456,11,24,,51,,12,,76,,,531,12,,,,24,56,,,,,118,,,,,,,,,,,,,,20,,,,,
123456,11,24,,51,,12,,76,,,531,12,,,,24,56,,,,,118,,,,,,,,,,,,,,20,,,,,
123456,11,24,,51,,12,,76,,,531,12,,,,24,56,,,,,118,,,,,,,,,,,,,,20,,,,,
...
123456,11,24,,51,,12,,76,,,531,12,,,,24,56,,,,,118,,,,,,,,,,,,,,20,,,,,
第一个数字是ID,其余是分数。我试图将此文件放入 c[42][1000] 的矩阵中以计算总分并按升序排列它们......但我面临的问题是: 到目前为止,该程序只计算第一行.... 任何想法如何让它存储所有这些?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int lines_allocated = 1000;
int max_line_len = 150;
double c[42][1000];
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
if (words==NULL)
{
fprintf(stderr,"Out of memory (1).\n");
exit(1);
}
FILE *fp = fopen("full list.txt", "r");
if (fp == NULL)
{
fprintf(stderr,"Error opening file.\n");
exit(2);
}
int i;
for (i=0;1;i++)
{
int j;
if (i >= lines_allocated)
{
int new_size;
new_size = lines_allocated*2;
words = (char **)realloc(words,sizeof(char*)*new_size);
if (words==NULL)
{
fprintf(stderr,"Out of memory.\n");
exit(3);
}
lines_allocated = new_size;
}
words[i] = (char*)malloc(max_line_len);
if (words[i]==NULL)
{
fprintf(stderr,"Out of memory (3).\n");
exit(4);
}
if (fgets(words[i],max_line_len-1,fp)==NULL)
break;
for (j=strlen(words[i])-1;j>=0 && (words[i][j]=='\n' || words[i][j]=='\r');j--)
;
words[i][j]='\0';
}
int j;
int k=i;
for(j = 0; j < k; j++)
{
printf("%s\n", words[j]);
char *pptr = words[j];
int l;
words[j][strlen(words)-1]=',';
for (l = 0; l < 41; l++)
{
char *ptr = strchr(pptr, ',');
if (ptr)
{
*ptr = 0;
c[l][j] = atof(pptr);
pptr = ptr + 1;
}
}
for (l = 0; l < 41; l++)
{
printf("%.2lf\n", c[l][j]);
}
return 0;
}
for (;i>=0;i--)
free(words[i]);
free(words);
return 0;
}
可能是矩阵根本不存储任何值。
【问题讨论】:
-
程序只计算第一行,
return 0;在循环中。还有错别字words[j][strlen(words)-1]=','; -
现在它不存储最后一个逗号后的值:(
标签: c csv file-io matrix type-conversion