0

我正在尝试创建一个程序,该程序将从多个文本文件中读取数据并比较每个文件中的数据。目前,我一直在尝试从列数和行数未知的文件中读取数据,直到用户在运行时指定长度。

过去我使用过 fscanf,但它总是有多少列以及它们被硬连线到程序中的变量类型,即fscanf(fp,"%d %d %d",&a,&b,&c). 是否可以使用一些东西,这样我就不必在代码中固有地编程说 3 个双指标?目前我有它,所以用户输入文件的数量,每个文件中的列和行。该程序的想法是始终比较相似的文件,因此它们需要始终具有相同的格式,即行数和列数。

当前代码是否有帮助:

int main(){
/* Ask for # of files */
printf("\nHow many files are you comparing\n");
int filnum;
scanf("%d",&filnum);

/* Ask for # of columns */
printf("How many columns of data are there?\n");
int colnum;
scanf("%d",&colnum);

/* Ask for length of rows */
printf("How many rows of data are there?\n");
int rownum;
scanf("%d",&rownum);

/* Read in file names */
char filea[filnum][50];
int i;
for (i=0; i<filnum; i++) {
    char temp[50];
    printf("Eneter file #%d please.\n",i+1);
    scanf("%s",temp);
    if(strlen(temp)>50){
        printf("Please shorten file to less than 50 char");
        exit(0);
    }
    strcpy(filea[i],temp);
}

/* Create data array on heap */
double* data = (double*)malloc(sizeof(double)*rownum*colnum*filnum);

/* Start opening files and reading in data */
for (i=0; i<filnum; i++) {
    FILE *fp;
    fp = fopen(filea[i],"r");
    if (fp==NULL) {
        printf("Failed to open file #%d",i+1);
        exit(1);
    }
    /* Attempt */
    int j,k;
    for (j=0; j<rownum; j++) {
        for (k=0; k<colnum; k++) {
            fscanf(fp," %lf",&data[i*rownum*colnum + j*colnum + k]);
            printf("%lf, ",data[i*rownum*colnum + j*colnum + k]);
        }
        printf("\n");
    }

    fclose(fp);
}

free(data);


return 0;
}

额外的真棒将以某种方式摆脱必须输入# of columns和# of rows,但我猜这已经超越了我自己。感谢你们提供的任何帮助。

4

1 回答 1

1

May be:

for (i=0; i<max; i++)
{
  fscanf (fp, " %f", &var[i])
}

You should allocate var to the length of at least max with type double of float

Or read an entire line with fgets then use strtok and strtod to get the floating point numbers.

于 2013-06-12T15:17:59.523 回答