-1

我有一个表格数据集

0.547,0.797,2.860,1.398,急右转

0.541,0.786,2.373,1.919,急右转

0.549,0.784,2.370,1.930,急右转

0.983,0.780,2.373,1.701,向前移动

0.984,0.780,2.372,1.700,向前移动

0.983,0.780,2.378,1.602,向前移动

0.983,0.780,2.381,1.701,向前移动

.
.


行 = 5456,第 5 列

在 MATLAB 中很容易将文本文件加载到数据矩阵中。但我在 C 中苦苦挣扎。我试过这段代码

int main()
{
    struct node {
        float at1;
        float at2;
        float at3;
        float at4;
        char at5[30];
    } record[ROW][COL];

    FILE *file;
    int i, j;

    memset(record, 0, sizeof(record)); 
    file = fopen("sensor.txt", "r");

    if (file == NULL) {
        printf("File does not exist!");
    } else {
        for (i = 0; i < ROW; ++i) {
            for (j = 0; j < COL; ++j) {
                fscanf(file, "%f,%f,%f,%f,%s", &record[i][j].at1, &record[i][j].at2, &record[i][j].at3, &record[i][j].at4, &record[i][j].at5);
            }   
        }   
    }   
    fclose(file);

    for (i = 0; i < ROW; ++i)
        for (j = 0; j < COL; ++j) {
            printf("%f\t%f\t%f\t%f\t%s\n", record[i][j].at1, record[i][j].at2, record[i][j].at3, record[i][j].at4, record[i][j].at5);
        }
    return 0;
}

0.000000只得到无限行和 4 列。

我想将前四列保存在一个矩阵中,最后一列保存为另一个列矩阵。我可以这样做吗?

我必须构建一个分类器,我在 MATLAB 中很容易做到,而不使用预定义的函数,但是在 C 中读取数据阻碍了我的代码。

我知道这可能是一个重复的问题,但我在其他线程中尝试了解决方案,它们不适用于我的数据集。

4

1 回答 1

2

首先,您已经定义了一个包含所有字段的记录,它们共同构成每一行。这意味着当您阅读时,您拥有一行的所有值,因此结构维度应该是可用的最大记录,即结构的一维数组record

但是你不能在堆栈上分配这么大的结构,它会溢出,最好在动态内存中分配它:

struct node {
    float at1;
    float at2;
    float at3;
    float at4;
    char at5[30];
} record;

struct node *record = malloc(sizeof(struct node) * MAXRECORDS);

另一个错误是,scanf结构的最后一个字段record已经是一个指向 char 的指针,所以你不需要取消引用它。

这是一个工作代码:

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

#define MAXRECORDS 10

int main(int argc, char *argv[])
{
    struct node {
        float at1;
        float at2;
        float at3;
        float at4;
        char at5[30];
    };

    struct node *record = malloc(sizeof(struct node) * MAXRECORDS);

    FILE *file;
    int nRecords = 0;

    memset(record, 0, sizeof(record));
    file = fopen("sensor.txt", "r");

    if (file == NULL)
    {
        printf("File does not exist!");
    }
    else
    {
        while (EOF != fscanf(file, "%f,%f,%f,%f,%s", &record[nRecords].at1, &record[nRecords].at2, 
                                &record[nRecords].at3, &record[nRecords].at4, record[nRecords].at5) && nRecords<MAXRECORDS)
        {
            nRecords++;
        }
    }

    fclose(file);

    for (int i = 0; i < nRecords; ++i)
    {
        printf("%f\t%f\t%f\t%f\t%s\n",
                record[i].at1, record[i].at2, 
                record[i].at3, record[i].at4, record[i].at5);
    }
    return 0;
}

在“真实”应用程序中,您希望将数组维度设置为足够大的值,并且当您到达分配空间的末尾时,您可以将其重新分配给其他数据。这使您可以在读取之前不知道其编号的情况下读取您想要多少条目的文件。

PS我添加了要读取的最大记录数的检查。但这仍然是一个示例,仍然缺少许多检查,即我不检查 malloc 返回的值。

于 2015-08-20T12:47:14.930 回答