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

さらに素晴らしいのは、列数と行数を入力する必要がなくなることですが、それは私が推測するよりも進んでいます。皆さんが提供できる助けをありがとう。

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 に答える