简体   繁体   English

如何读取 .csv 文件并将其保存到二维数组中?

[英]How do I read a .csv file and save it into a 2d array?

I am quite new to C programming and I have been set the task of reading a .csv file containing a 2d integer array, I need to then print it so it shows up in the terminal.我对 C 编程很陌生,我已经设置了读取包含 2d 整数数组的 .csv 文件的任务,然后我需要打印它以便它显示在终端中。 The array is a 4 row by 2 col integer array, but when I use this code I get a random list of numbers.该数组是一个 4 行 x 2 列整数数组,但是当我使用此代码时,我会得到一个随机数字列表。 I have attached the code I used and the .csv file array and how it should look like.我附上了我使用的代码和 .csv 文件数组以及它应该是什么样子。

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

int main()
{
    FILE *in_data = fopen("in.csv", "r");
    
    int i;
    int j;
    int trIn[4][2];
    if(in_data == NULL)
    {
        printf("error\n");
        return 1;
    }
    for(i = 0; i < 4; i++){
    for(j = 0; j < 2; j++){
        char junk;

        if (j != 0) fgetc(in_data);

        fscanf(in_data, "%c%d%c", &junk, &trIn[i][j], &junk);
        printf("%d ", trIn[i][j]);
    }
    fgetc(in_data);
    printf("\n");
    }
return 0;
}
    

.csv file array: .csv 文件数组:

0 0
0 1
1 0
1 1

.csv file (raw): .csv 文件(原始):

"0","0"
"0","1"
"1","0"
"1","1"

You can create a pattern which discards the unwanted characters, like so:您可以创建一个丢弃不需要的字符的模式,如下所示:

Live demo 现场演示

for (i = 0; i < 4; i++)
{
    for (j = 0; j < 2; j++)
    {
        //printf("%s", str); //print str to check if there are any weird chars
        fscanf(in_data, " \"%d\",", &trIn[i][j]);
        printf("%d ", trIn[i][j]);
    }
    printf("\n");
}

Chek if you have spaces in the lines after the values, that can throw fscanf off.如果值后面的行中有空格,则可以检查fscanf Although a space before the specifier, like in the sample, should solve that.尽管在说明符之前有一个空格,就像在示例中一样,应该可以解决这个问题。

Also, you can export .csv files without the quotation marks, if that's something you can control.此外,您可以导出不带引号的.csv文件,如果这是您可以控制的。

You can also try a more robust method using a combo of fgets and sscanf :您还可以使用fgetssscanf的组合来尝试更强大的方法:

Live demo 现场演示

char str[20];
int i = 0;
int j = 0;

//...

while (i < 4 && fgets(str, sizeof str, in_data))
{
    //printf("%s", str); //print str to check if there are any weird chars
    if(sscanf(str, "\"%d\",\"%d\"", &trIn[i][j], &trIn[i][j+1]) == 2)
        printf("%d %d\n", trIn[i][j], trIn[i][j+1]);
    i++;
}

You can replace you current loop with this one:您可以用这个替换当前循环:

for(i = 0; i < 4; i++){
    for(j = 0; j < 2; j++){
        char junk;

        if (j != 0) fgetc(in_data);

        fscanf(in_data, "%c%d%c", &junk, &trIn[i][j], &junk);
        printf("%d ", trIn[i][j]);
    }
    fgetc(in_data);
    printf("\n");
}

This works because fscanf(in_data, "%d", &trIn[i][j]) reads an int ( %d ) from the file in_data into the memory location of trIn[i][j] .这是有效的,因为fscanf(in_data, "%d", &trIn[i][j]) ) 从文件in_data读取一个 int ( %d ) 到trIn[i][j]的内存位置。 fgetc didn't work because it only reads a single character which was then printed as if it were an integer. fgetc不起作用,因为它只读取一个字符,然后将其打印为整数。

EDIT: Now, for each value in the .csv file, you read to a junk variable the " and \\n characters.编辑:现在,对于 .csv 文件中的每个值,您将"\\n字符读入垃圾变量。

Line by line:逐行:

if (j != 0) fgetc(in_data); reads the , from the csv file into a junk variable (which isn't the first character on a line).,从 csv 文件读入垃圾变量(不是一行的第一个字符)。

fscanf(in_data, "%c%d%c", &junk, &trIn[i][j], &junk); reads:读到:

  • 1st: the opening " character into a junk variable第一:开头的"字符变成垃圾变量
  • 2nd: the number (int: %d ) into to memory location of trIn[i][j] .第二:进入trIn[i][j]内存位置的数字(int: %d )。
  • 3rd: the closing " character into a junk variable第三个:结束"字符变成垃圾变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM