简体   繁体   English

使用fscanf(C)从文件中提取双精度

[英]Extract double from a file with fscanf (C)

Here is my problem, I have those data : 这是我的问题,我有那些数据:

  // input 1        input 2         output
  -2.9300000e+00  -8.3227505e-01  -7.4588269e+00
   1.1500000e+00   6.7039029e-01   6.3757647e-02
  -3.6000000e-01  -3.9144914e-01   5.9973550e-01
   7.0000000e-01   1.1649989e+00  -2.0060024e+00
  -1.7900000e+00  -4.9222540e-02  -4.7662334e+00
  -9.0000000e-02  -1.4490347e+00  -1.3910318e+00

And I want to put them in an array, but nothing works. 我想将它们放在一个数组中,但是没有任何效果。 I have tried to move with fgetc and fseek, and it seems my code understands the format I want, but my array is always empty at the end of the run. 我尝试使用fgetc和fseek进行移动,似乎我的代码了解我想要的格式,但是在运行结束时我的数组始终为空。 Here is my current code : 这是我当前的代码:

int hauteur = 6;
int largeur = 3;
FILE* fichier = NULL;
Data data;
data.dimDonnees = largeur;
data.nombreDonnees = hauteur;
int i, j, c;
double **tab;

// Attribution dynamique de mémoire
tab = creerMatrice(hauteur, largeur);

if ((fichier = fopen(nomFichier, "r+")) == NULL ) {
    printf("Erreur lors du chargement de %s",nomFichier);
}

// On passe la première ligne de caractères
for(i=0;i<43;i++){fgetc(fichier);}

for (i=0; i<hauteur; i++) {
    for (j=0; j<largeur; j++) {
        // On avance jusqu'à ce que le caractère ne soit ni un espace ni un retour chariot
        while( (c = fgetc(fichier)) == 32 || c == 10 ){}
        fseek(fichier,-1,SEEK_CUR);
        fscanf(fichier, "%e", &tab[i][j]);
    }
}

And eventually here is the function creerMatrice() : 最后是函数creerMatrice():

double** creerMatrice(int n, int p) {
    double** tab;
    int i;
    tab = malloc(n*sizeof(*tab));
    for(i=0;i<n;i++) {
        tab[i]=malloc(p*sizeof(**tab));
    }
    return tab;
}

Actually, now it works, I don't really know why but it works ! 实际上,现在它可以了,我真的不知道为什么,但是它可以了! I juste replace 我只是替换

 fscanf(fichier, "%e", &tab[i][j]);

by 通过

 fscanf(fichier, "%le", &tab[i][j]);

and I move back one more time with fseek. 和fseek再回头一次。

tab[][] holds doubles, but you were using the scanf code for floats. tab [] []保留双打,但您使用的是scanf代码进行浮点运算。 fscanf() would write the binary 32-bit floating point representation of a number into memory, and the same binary value would later be interpreted as a double, which would result in a much different value. fscanf()会将数字的二进制32位浮点表示形式写入内存,并且相同的二进制值稍后将被解释为double,这将导致值大不相同。 scanf, printf, etc. don't perform any implicit casting - they interpret memory exactly as given using the codes given, so they always have to match the actual data type for the result to be meaningful. scanf,printf等不执行任何隐式强制转换-它们使用给定的代码完全按照给定的方式解释内存,因此它们必须始终与实际数据类型匹配才能使结果有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM