c - 将制表符分隔的数据读取到 C 中的数组

标签 c arrays file-io

我有一个文本格式的输入文件,如下所示:

G:  5   10  20  30
C:  24  49  4.0 30.0

我想分别将它们中的每一个设置为一个数组,数组。我从这个答案中看到reading input parameters from a text file with C ,一种读取某些值的方法,但我如何获取数组 G 和 C?

编辑:

如果我从 .txt 文件中删除 G: 和 C:,我可以只运行一个 for 循环。

double *conc = (double*)malloc(properConfigs*sizeof(double));
double *G = (double*)malloc(properConfigs*sizeof(double));

for (int i=0;i<properConfigs;i++)
    fscanf(inputfile,"%lf", &G[i]);
for (int i=0;i<properConfigs;i++)
    fscanf(inputfile,"%lf", &conc[i]); 

这可行,但我希望能够说明有人以不同的顺序保存 .txt 文件或在某个时候添加更多行(使用不同的参数)。

最佳答案

我不是 scanf 的粉丝,强烈建议您自己解析该行。如果您坚持使用 scanf,我建议为此使用 sscanf 变体,这样您就可以事先检查该行以查看要写入哪个数组。不过,我不确定您为什么要使用命名数组。 C 不太擅长自省(introspection),您可以使程序更加灵活,而无需尝试将您的输入与特定符号联系起来。像这样的东西:

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

#define properConfigs 4
void *Malloc(size_t s);
int
main(int argc, char **argv)
{
        FILE *fp = argc > 1 ? fopen(argv[1],"r") : stdin;
        double *G = Malloc( properConfigs * sizeof *G );
        double *C = Malloc( properConfigs * sizeof *G );
        int line_count = 0;
        char line[256];

        if( fp == NULL ) {
                perror(argv[1]);
                return 1;
        }
        while( line_count += 1, fgets( line, sizeof line, fp ) != NULL ) {
                double *target = NULL;
                switch(line[0]) {
                case 'G': target = G; break;
                case 'C': target = C; break;
                }
                if( target == NULL || 4 != sscanf(
                                line, "%*s%lf%lf%lf%lf",
                                target, target+1, target+2, target+3)) {
                        fprintf(stderr, "Bad input on line %d\n", line_count);
                }
        }
        for(int i=0; i < 4; i += 1 ) {
                printf ("G[%d] = %g\tC[%d] = %g\n", i, G[i], i, C[i]);
        }


        return ferror(fp);
}
void *Malloc(size_t s) {
        void *r = malloc(s);
        if(r == NULL) {
                perror("malloc");
                exit(EXIT_FAILURE);
        }
        return r;
}

关于c - 将制表符分隔的数据读取到 C 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364452/

相关文章:

c - 为什么我的数组中有我没有分配的值?

javascript - 从使用 ajax 发布的序列化数组创建多维数组

c - 将输入文件传递给 C 中的输出文件?

运行少量线程时 CPU 使用率达到 100%

c - 如何包含包装到新 dll 中的 dll 文件?

python - Ctypes:分配 double** ,将其传递给 C,然后在 Python 中使用

c++ - 为什么对 read() 的调用会永远阻塞

c++ - 为什么要在 Linux 中挂载文件

Python 服务器 "Aborted (Core dumped)"

c - 如何将 for 循环中的数据存储到变量中以供其他计算?