gpt4 book ai didi

c - 将 CSV 文件存储到 C 中的 Float Matrix

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:48 25 4
gpt4 key购买 nike

代码没有将行的最后一个逗号之后的值存储到矩阵中...

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

最佳答案

我认为你错过了一个简单的案例:应该是

#include <ctype.h>
...
char *ptr = strchr(pptr, ',');
if (ptr)
{
*ptr = 0;
c[l][j] = atof(pptr);
pptr = ptr + 1;
}
else if (isdigit(*pptr)) {
c[l][j] = atof(pptr);
}

关于c - 将 CSV 文件存储到 C 中的 Float Matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20728653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com