Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c中文本文件(int、string、string和float)的fscanf和fgets_C_String_File_Scanf_Fgets - Fatal编程技术网

c中文本文件(int、string、string和float)的fscanf和fgets

c中文本文件(int、string、string和float)的fscanf和fgets,c,string,file,scanf,fgets,C,String,File,Scanf,Fgets,我试图用一个文本文件创建4个数组。文本文件如下所示: 1000 Docteur Albert 65.5 1001 Solo Hanz 23.4 1002 Caillou Frederic 78.7 … 守则: void creer (int num[], char pre[][TAILLE_NP+1], char nom[][TAILLE_

我试图用一个文本文件创建4个数组。文本文件如下所示:

1000 Docteur             Albert              65.5
1001 Solo                Hanz                23.4
1002 Caillou             Frederic            78.7
…
守则:

void creer (int num[], char pre[][TAILLE_NP+1], char nom[][TAILLE_NP+1], 
float note[], int * nb ){

  int  n = 0, i; /*nb personnes*/

  FILE *donnees = fopen("notes.txt", "r");

  if(!donnees){
    printf("Erreur ouverture de fichier\n");
    exit(0);
  }

  while (!feof(donnees)){

    fscanf(donnees,"%d", &num [n]);
    fgets(nom[n], TAILLE_NP+1, donnees);
    fgets(pre[n], TAILLE_NP+1, donnees);
    fscanf(donnees,"%f\n", &note[n]);

    printf("%d %s %s %f\n",num[n], nom[n], pre[n], note[n]);
    n++;
    }

  fclose (donnees);

  *nb = n ;
  }


int main() {

  int num[MAX_NUM];
  int nbEle;

  char pre[MAX_NUM][TAILLE_NP+1],
       nom[MAX_NUM][TAILLE_NP+1];

  float note[MAX_NUM];

  creer (num, pre, nom, note, &nbEle);

  printf("%s", pre[2]); //test

  return 0; 
}
问题是,我相信有更好的方法来创建数组,我是个初学者。另外,浮点也有问题,当我打印F时,小数点不正确。例如,78.7变为78.699997。 我做错了什么? 谢谢!:)

这里有几个问题:

浮点运算非常棘手。阅读(并记住该URL)

不要在你的工作上分配太多。一个典型的调用帧应该不超过几千字节(并且您的整个调用堆栈应该少于一个或几兆字节)。使用

C只有一维数组。如果需要更好的方法,可以创建一些抽象数据类型(通常避免数组的数组)。看一看,寻找灵感

仔细阅读每个标准函数的定义。您应该在此处测试两个问题的结果:

  • 混合使用
    fscanf()
    fgets()
    是一个坏主意,因为前者适用于部分生产线,后者适用于整个生产线

  • float
    并不像您期望的那样精确


  • 要解决1:

    fscanf(donnees, "%d", &num[n]);
    fscanf(donnees, "%s", nom[n]);
    fscanf(donnees, "%s", pre[n]);
    fscanf(donnees, "%f\n", &note[n]);
    
    为了避免“字符串”溢出,您可以告诉
    fscanf()


    要解决第二个问题:

    注释
    be
    double
    s并执行

    fscanf(donnees,"%lf\n", &note[n]);
    

    解决2成功了!谢谢但是解决1不起作用。当我更改代码时,执行非常混乱,0.0000 for note[n]@SamuelGirard:“没有工作”的意思是什么?不管怎样,这只是printf。忘记将%f更改为%lf。非常感谢@SamuelGirard打印
    double
    s时,无需使用长度修饰符
    l
    。如果没有它,它将正常工作。