首页 > 解决方案 > 一次将一行二维数组存储在一起

问题描述

我有一个问题,将我同时从文件 csv 读取的行的所有值一起存储到二维数组中。

这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define BUFSIZE 1024

int main()
{    
    char *filename = "pb0.csv";
    char str[BUFSIZE];
    FILE *fpr;
    fpr = fopen(filename, "r");
    int i,j;
    const int row = 449;
    const int column = 6;
    int family[row][column];
    int c,d,e,f,g,h;


    if (fgets(str, BUFSIZE, fpr) != NULL) {
        while(fscanf(fpr, "%d; %d; %d; %d; %d; %d", &c,&d,&e,&f,&g,&h) != EOF){
            for(i=0;i<row;i++){
                for(j=0;j<column;j++){
                    //add code here
                }
            }
        }
    }

    //printf("%d",n);
    fclose(fpr);

    return 0;
}

任何帮助将不胜感激。

标签: cmultidimensional-arraystore

解决方案


我会说您显示的代码至少有两个问题。首先是您阅读并忽略了第一行。第二个是你不能很好地处理错误。第三是您从文件中读取一个“行”,然后遍历所有二维数组(当您只需要设置单行的值时)。

通过一些更改,您可以解决所有这三个问题(第三个问题似乎是您要问的):

int current_row = 0;

// Read all lines in a loop
while (fgets(str, BUFSIZE, fpr) != NULL)
{
    // Parse the line we just read, read directly into the row
    if (sscanf(str, "%d; %d; %d; %d; %d; %d",
               &family[current_row][0],
               &family[current_row][1],
               &family[current_row][2],
               &family[current_row][3],
               &family[current_row][4],
               &family[current_row][5]) == 6)
    {
        // Parsing successful, advance to the next row
        ++current_row;
    }
}

// All data read from the file
// The number of lines that was actually read and successfully parsed is in
// the variable current_row

// Example iterating over all records that were read from the file
for (int i = 0; i < current_row; ++i)
{
    printf("family[%d][0] = %d\n", i, family[i][0]);
}

推荐阅读