Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: _OLAYA_ en 16 Diciembre 2016, 21:50 pm



Título: duda con array de estructuras
Publicado por: _OLAYA_ en 16 Diciembre 2016, 21:50 pm
tengo un fichero txt organizado en columnas, la primera tiene un numero entero del 1 en adelante, la segunda tiene un nombre y la tercera un precio. El caso es que no soy capaz de cargar el fichero en mi programa.  

Código
  1. #include<stdio.h>
  2. #define CadNom 30
  3. #define NumPro 100
  4. struct carta
  5. {
  6.    int CodProducto;
  7.    char nombre[CadNom];
  8.    float precio;
  9.  
  10. };
  11. struct carta productos[NumPro];
  12.  
  13. void cargarCarta(FILE *f, struct carta productos[NumPro], int *tamanio);
  14. void imprimirCarta(struct carta productos[NumPro], int tamanio);
  15. main()
  16. {
  17.    FILE *fich;
  18.    int tamanio;
  19.  
  20.    fich = fopen("carta.txt", "r");
  21.  
  22.    if(fich == NULL) return -1;
  23.  
  24.    cargarCarta(fich, productos, &tamanio);
  25.  
  26.    fclose(fich);
  27.  
  28.    imprimirCarta(productos, tamanio);
  29. }
  30.  
  31. void cargarCarta(FILE *f, struct carta productos[NumPro], int *tamanio)
  32. {
  33.    /* CARGA LA CARTA AL PROGRAMA */
  34.    int i=0;
  35.  
  36.    while(fscanf(f, "%d" "%s" "%f", &productos[i].CodProducto, productos[i].nombre, &productos[i].precio) != EOF)
  37.    {
  38.        i++;
  39.    }
  40.    *tamanio = i;
  41. }
  42.  
  43. void imprimirCarta(struct carta productos[NumPro], int tamanio)
  44. {
  45.    /*SE IMPRIME LA CARTA*/
  46.    int i=0;
  47.  
  48.    printf("Codigo del producto\tNombre\t\tProducto");
  49.    printf("\n el tamanio es %d", tamanio);
  50.    while (i < tamanio)
  51.    {
  52.        printf("%d\n", productos[i].CodProducto);
  53.        i++;
  54.    }
  55.  
  56. }
  57.  


Mod: No escribir en mayúsculas


Título: Re: duda con array de estructuras
Publicado por: _OLAYA_ en 17 Diciembre 2016, 01:11 am
Ya lo he conseguido, para hacerme menos lió he separado los fscanf

Código
  1. fscanf(f, "%d", &productos[i].CodProducto);
  2. fscanf(f, "%s", productos[i].nombre);
  3. fscanf(f, "%f", &productos[i].precio);


Y luego un fallo de concentración, después del valor de cada precio tenía un espacio y el símbolo del euro en el fichero.