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

Read tab delimited data to array in C

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

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 文件或在某些时候添加更多行(使用不同的参数)。

看起来你的问题是 atof() 在 c 中丢弃第一个有效数字后的任何白色 space。如果您想获得所有数字,则必须拆分 tmpstr2 并在 atof() 中分别处理每个元素。

您可以使用 strtok 将其拆分为标记,然后在每个标记上使用 atof()

char temp[];
char *nums;
nums = strtok(temp, " \t");
int count = 0;
while (nums != NULL)
{
    G[count] = atof(chrs);
    nums = strtok(NULL, " \t");
    count++;
}

当然,前提是您事先知道您将获得多少个号码。

查看这篇文章了解更多信息:Split string with delimiters in C

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

#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;
}