1
代碼不在行成矩陣的最後一個逗號後的值存儲...存儲CSV文件到浮點數矩陣用C
full list.csv
是這樣的:
123456,57,45,,67,,56,,63,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,,1523521
123457,57,45,,67,,56,,634,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,1234,,
123458,57,45,,67,,56,,63,,,724,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,1234,
123459,57,45,,67,,56,,63,,,72,647,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,,1234
123450,57,45,,67,,56,,63,,,72,67,,,,344,56,,,,,56,,,,,,,,,,,,,,45,,,,,124
123451,57,45,,67,,56,,63,,,72,67,,,,34,564,,,,,56,,,,,,,,,,,,,,45,,,,,
123452,57,45,,67,,56,,63,,,72,67,,,,34,56,,,,,564,,,,,,,,,,,,,,45,,,,,124
123453,57,45,,67,,56,,63,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,454,,,,,
123454,57,45,,67,,56,,63,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,,124
123455,574,45,,67,,56,,63,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,,
123465,57,454,,67,,56,,63,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,,
123466,57,45,,674,,56,,63,,,72,67,,,,34,56,,,,,56,,,,,,,,,,,,,,45,,,,,124
這是我的代碼:
#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.csv", "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;
for (l = 0; l < 42; l++)
{
char *ptr = strchr(pptr, ',');
if (ptr)
{
*ptr = 0;
c[l][j] = atof(pptr);
pptr = ptr + 1;
}
}
}
int l;
for (j = 0; j < k; j++)
{
printf("\n");
for (l = 0; l < 42; l++)
{
printf("%.2f\t", c[l][j]);
}
}
for (;i>=0;i--)
free(words[i]);
free(words);
return 0;
}
如何使用調試器來調試代碼?跟蹤它並找到錯誤。 – alk