我有數據的多個TEXTFILES如下讀取科學格式號碼℃。這兩列數據由製表符分隔。我正在試圖將這個數據文件讀入程序中作進一步處理。這是我寫的代碼如下:問題使用的fscanf()
#include <stdio.h>
#include <stdlib.h>
float **make_array(int size); //function to make 2D array
int main(int argc, char **argv)
{
FILE *infile;
infile=fopen(argv[1], "r");
//count number of lines in file
char c;
int i=0, numlines=0;
while((c=fgetc(infile))!=EOF)
if(c == '\n') numlines++;
printf("numlines: %d\n", numlines);
float **entry = make_array(numlines);
//read inputfile
for(i=0; i< numlines; i++)
fscanf(infile, " %G\t%G", &entry[0][i], &entry[1][i]);
//verify read values
printf("\n");
for(i=0; i<numlines; i++)
printf("%E\t%E\n", entry[0][i], entry[1][i]);
//clean up before exiting
free(entry[0]);
free(entry[1]);
free(entry);
fclose(infile);
return 0;
}
//create a 2D array of 2 by {size}
float **make_array(int size){
int i;
float **entry = malloc(2*sizeof(float *));
if(entry==NULL) exit(1);
entry[0] = malloc(size*sizeof(float *));
for(i=0;i<size;i++) entry[0][i] == 0.0;
entry[1] = malloc(size*sizeof(float *));
for(i=0;i<size;i++) entry[1][i] == 0.0;
return entry;
}
當我編譯並運行程序,它打印出的文件中正確的行數,但printf語句來驗證讀入陣列entry
只是打印數據出全零,如下圖所示:
numlines: 252
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
0.000000E+00 0.000000E+00
我嘗試了不同的格式說明fscanf
像%g,%e,%f,%G etc
但他們都給予同樣的結果。另外,我正在使用Ubuntu 12.04和GCC 4.6。任何指向什麼是錯誤的指針將不勝感激。
Khadija。
你調試了嗎?爲什麼使用「%G \ t%G」你確定在中間有一個'\ t'字符 –