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

时间:2019-05-29 15:55:42

标签: 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?

EDIT

如果我从.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文件,或者有时添加更多行(具有不同的参数)。

2 个答案:

答案 0 :(得分:1)

我不是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;
}

答案 1 :(得分:0)

看起来您的问题是c中的atof()丢弃了第一个有效数字之后的任何空格。如果要获取所有数字,则必须拆分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

相关问题