【问题标题】:Store a row of two dimensional-array together at a time一次将一行二维数组存储在一起
【发布时间】:2020-03-06 10:05:33
【问题描述】:

我在存储我从文件 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;
}

任何帮助将不胜感激。

【问题讨论】:

    标签: c multidimensional-array store


    【解决方案1】:

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

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

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

    【讨论】:

    • 第一行是csv文件中每一列的标题,所以没有问题。不管怎样,谢谢你的改进!!我会尝试测试它!
    猜你喜欢
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2020-10-06
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多