如何在C中从文件读取大量列到数组?

问题描述 投票:0回答:1

我想使用C从文件到2d数组读取大列(未知列数)。每行的列数是恒定的。列在文件中用一个空格('')分隔。

我尝试在循环内部进行循环,但是没有成功。我还设法编写了一个计算列数的代码,但据我所知。我是编程的新手,因此将不胜感激。我使用的代码如下

int readData(char *filename, FILE *f) {

int lines;
int count = 0;
float dataArray [lines][count];    
int i,j; 
char c;

f = fopen(filename, "r");
if (f == NULL) return -1;



for (c = getc(f); c != '\n'; c = getc(f)) {
    if (c == '\t')
        count++;
}


printf("Your file %s consists of %d columns\n", filename, count); 
printf("Set the length: ");
scanf("%d", &lines);



for(int i=0;i<lines;i++){
        for(int j=0;j<count;j++){
            fscanf(f,"%f", &dataArray[i][j]);
        }
}




 for (i=0; i<lines; i++){
    for (j=0;j<count;j++){
        printf("%.3f",dataArray[i][j]);}
        printf("\n");
        }
  printf("\n");  
  fclose(f);
return 0;      
}

int main (int argc, char *argv[], char filename[512]) {

FILE *f;
printf("Enter the file name: ");
if (scanf("%s", filename) != 1) {
    printf("Error in the filename\n");
    return -1;}

if (readData(filename, f) == -1) {
    printf("Error in file opening\n");
    return -1;}
return 0;
}

数据输入如下:217,526 299,818 183,649 437,536 213,031 251 263,275 191,374 205,002 193,645 255,846 268,866 2,516 \ n229,478 304,803 184,286 404,491 210,738 237,297 279,272 189,44 202,956 204,126 242,534 276,068 2,163 \ n

但是从中得到一个理想长度的数组,但是其余的都是错误的,看起来像这样:225.0000000.000000-1798259351694660865572287994621067264.0000000.0000000.0000000.0000000.0000000.0000000.0000000.00000014037667868815752572174336.0000000.000000 \ n225.0000000.000000-1798259351694660865572287994621067264.0000000.0000000.0000000.0000000.0000000.0000000.0000000.00000014037667868815752572174336.0000000.000000 \ n

全部重复感谢您的帮助。

c arrays readfile
1个回答
0
投票

您的目标数组必须是动态的。您正在使用未初始化的数据创建静态数组:

float dataArray [lines][count]; // line is not initialized, and count = 0

将其更改为此:

声明:

float dataArray**;

初始化:

// only after setting count and lines
dataArray = new float[lines];
for (int i = 0; i < lines; ++i) {
    dataArray[i] = new float[count];
}

清理:当不再需要为dataArray分配的内存时,必须释放它:

for (int i = 0; i < lines; ++i) {
    delete[] dataArray[i];
}
delete[] dataArray;
© www.soinside.com 2019 - 2024. All rights reserved.