elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


  Mostrar Mensajes
Páginas: [1]
1  Programación / Programación C/C++ / Re: Programa Loteria en: 19 Enero 2013, 15:59 pm
Mi fallo esta en la forma de leer el txt, me lee una palabra por bucle, cuando yo quiero leer la línea completa para que así cuando compare con "Sin vender" encuentre coincidencias. Porque ahora lee una sola palabra por bucle y no da ninguna coincidencia porque compara un solo espacio del lugar (sin o vender) con sin vender, y claro, no lo encuentra. Gracias
2  Programación / Programación C/C++ / Re: Programa Loteria en: 19 Enero 2013, 02:05 am
esta precticamente todo, me imprime en el fichero result, me imprime en el fichero premios.txt y me lee el premios txt pero me queda que me imprima eso ultimo leido me lo imprima de la forma:
Primer premio: 949 8 Sin vender
Segundo premio: 5354 2 Lugo
etc que lo que me hace ahora es imprimirmelo todo seguido. Está de la seguiente manera:

void leerymostrarficherotxt(char *fichtxt){
        FILE *premiotxt;
        char lugar[91];
        //Abrir fichero para lectura de los numeros
     if ((premiotxt = fopen(fichtxt, "r")) == NULL){
        //Si no puede abrise o no existe.
        printf("El fichero '%s' no se puede leer", fichtxt);
        }
     else printf("\n    NUMEROS DE PREMIADOS:\n");
         fscanf (premiotxt,"%s", lugar);
        //Muestra datos por pantalla
        while ( !feof(premiotxt)){                      //Mientras no ha llegado a la marca de fin de fichero lee linea a linea
          printf("%s\t", lugar);                  //Escribe una de las lineas en la pantalla.
          fscanf(premiotxt, "%s", lugar);      //Lee siguiente linea hasta fin de linea o un maximo de 90 caracteres.
                      }
     fclose (premiotxt);
        }



void ponersinvender(char *fichtxt){
        FILE *premiosinvend;
        char lugar[91];

        if ((premiosinvend = fopen(fichtxt, "r")) == NULL){
          //Si no puede abrise o no existe.
           printf("El fichero '%s' no se puede leer", fichtxt);}
        else {printf("\nPremios que no se han vendido:\n");
                fscanf(premiosinvend, "%s", lugar);

          //Muestra datos por pantalla
              while ( !feof(premiosinvend)){                      //Mientras no ha llegado a la marca de fin de fichero lee linea a l$
                if (strstr (lugar, "Sin vender")){     //Si la cadena de busqueda esta incluida en dato
                  printf("%s", lugar);}
                 fscanf(premiosinvend, "%s", lugar);       //Lee la siguiente linea del fichero.
                }
        fclose(premiosinvend);
   }}

si podeis echarle un ojo al de mostrar sin vender que no muestra tambien estaria bien ;) gracias
3  Programación / Programación C/C++ / Re: Programa Loteria en: 17 Enero 2013, 11:44 am
Viendo nuestro programa nos podrías poner como harías tu el procedimiento buscar, porque a mi me da un bucle infinito y violación del segmento al final, creo que tengo mal hecho el do-while, con esto tendría completo el programa así que estaría muy agradecido si me lo pudieras decir.
4  Programación / Programación C/C++ / Re: Programa Loteria en: 16 Enero 2013, 20:27 pm
no es ese nuestro problema, necesitamos tener bien el procedimiento buscar, si alguien viendo como esta organizado nuestro programa nos puede ayudar a hacerlo estaría muy agradecido.
5  Programación / Programación C/C++ / Re: Programa Loteria en: 16 Enero 2013, 11:07 am
ok esta corregido os paso el codigo mas avanzado y si me podeis aconsejar para que no viole el segmento porque no se donde puede ser:
Código
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define TAM 7
  5. //definicion de estructuras
  6.  
  7. struct fnum { int numero; int serie;}; //estructura del vector premios
  8. struct registro { struct fnum billete; char lugar[30];}registro;
  9. struct cadenacar{ char cad[16];};
  10.  
  11.  
  12. /*definicion de funciones */
  13.  
  14. void inicializa_generador_aleatorios(){
  15.        /* Inicializa generador de n&#65533;meros aleatorios
  16.         E: (ninguna) S: (ninguna)*/
  17.        srand( time(NULL) );
  18.        }
  19.  
  20. int azar_numero( int tope ){
  21.        /* Funcion. Devuelve un entero al azar, menor que tope */
  22.        /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio
  23. / 1 <= valor devuelto <=tope */
  24.        return 1+(int)((float)tope*rand()/(RAND_MAX+1.0));
  25.        }
  26.  
  27. int azar_serie( int tope ){
  28.        /* Funcion. Devuelve un entero al azar, menor que tope */
  29.        /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio / 1 <= valor devuelto <=tope */
  30.        return 1+(int)((float)tope*rand()/(RAND_MAX+1.0));
  31.        }
  32.  
  33.  
  34. void buscar(struct fnum elegido[TAM], char *fichero1, char *fichero2, char *fichero3) { //para buscar los numeros en fichnumeros
  35.        struct cadenacar categoria[TAM];
  36.        char lugar[30];
  37.        int i, x;
  38.        int seguir;
  39.        int numero[TAM], serie[TAM];
  40.        struct registro registro;
  41.        FILE *result; /* result apunta a "result.dat"*/
  42.        FILE *fich;   // fich apunta a "fichnumerosCompletos.dat"
  43.        FILE *premiotxt;  // premiostxt apunta a "premios.txt"
  44.  
  45.     /* Apertura en modo lectura-escritura. */
  46.     fich = fopen("fichnumerosCompleto.dat", "r");
  47.     result = fopen("result.dat", "wr");
  48.     premiotxt = fopen("premios.txt", "w");
  49.  
  50.        if (result != NULL && fich !=NULL && premiotxt !=NULL);{ /*Comprobación*/
  51.  
  52.        seguir = 1;
  53.        while (seguir == 1){
  54.            do {
  55.                fread(&registro, sizeof(struct registro), 1, fich);
  56.                for(i =0; i<TAM; i++){
  57.                if ((elegido[i].numero == registro.billete.numero) && (elegido[i].serie == registro.billete.serie)) {
  58.                  //almacena lugar
  59.                        fprintf(result, "%d\t %d\t %s\n",registro.billete.numero, registro.billete.serie,registro.lugar);
  60.                        numero[i] = registro.billete.numero;
  61.                        serie[i]  = registro.billete.serie;
  62.                        lugar[i] = *registro.lugar;
  63.                        seguir = 0;
  64.                        }
  65.                  }
  66.                }while (!feof(fich));
  67.        fclose(fich);
  68.        fclose(result);
  69.        }
  70.                        for (i = 0; i < TAM; i++){
  71.                                            if (i==0)
  72.                                                strcpy(categoria[0].cad, "Primer premio:");
  73.                                            if (i==0)
  74.                                                strcpy(categoria[0].cad, "Primer premio:");
  75.                                            if(i== 1)
  76.                                                strcpy(categoria[1].cad, "Segundo premio:");
  77.                                            if (i==2)
  78.                                                strcpy(categoria[2].cad, "Tercer premio:");
  79.                                            if ((i <= TAM/2)&&(i>2)){
  80.                                                 strcpy(categoria[3+i].cad, "Cuarto premio:");
  81.                                                 x=i;}
  82.                                                else
  83.                                                 strcpy(categoria[1+x].cad, "Reintegro:");
  84.        }
  85.        //los escribimos en premios.txt
  86.        if ((numero[i] > 0 && numero[i] < 10000) && (serie[i] > 0 && serie[i] < 11))
  87.             fprintf(premiotxt,"%s\t%d\t%d\t%s\n",categoria[i].cad, numero[i], serie[i], lugar[i]);
  88.    }
  89.    fclose(premiotxt);//Cerramo el fichero txt
  90. }
  91.  
  92.  
  93. void leerficherotxt(char *fichtxt){
  94.        FILE *premiotxt;
  95.        char lugar[91];
  96.        //Abrir fichero para lectura de los numeros
  97.     if ((premiotxt = fopen(fichtxt, "r")) == NULL){
  98.        //Si no puede abrise o no existe.
  99.        printf("El fichero '%s' no se puede leer", fichtxt);
  100.        }
  101.     else printf("\n    NUMEROS DE PREMIADOS:\n");
  102.        fscanf (premiotxt, lugar , 91, fichtxt);
  103.        //Muestra datos por pantalla
  104.        while ( !feof(premiotxt)){                      //Mientras no ha llegado a la marca de fin de fichero lee linea a linea
  105.          printf("%s", lugar);                  //Escribe una de las lineas en la pantalla.
  106.          fscanf(premiotxt, lugar, 91, fichtxt);        //Lee siguiente linea hasta fin de linea o un maximo de 90 caracteres.
  107.        }
  108.     fclose (premiotxt);
  109.        }
  110.        }
  111.  
  112. void ponersinvender(char *fichtxt){
  113.        FILE *premiosinvend;
  114.        char lugar[91];
  115.  
  116.        if ((premiosinvend = fopen(fichtxt, "r")) == NULL){
  117.          //Si no puede abrise o no existe.
  118.           printf("El fichero '%s' no se puede leer", fichtxt);}
  119.        else {printf("\nPremios que no se han vendido:\n");
  120.                fscanf(premiosinvend, lugar , 91, fichtxt);
  121.             //Muestra datos por pantalla
  122.              while ( !feof(premiosinvend)){                      //Mientras no ha llegado a la marca de fin de fichero lee linea a l$
  123.                if (strstr (lugar, "Sin vender")){     //Si la cadena de b&#65533;squeda esta incluida en dato
  124.                  printf("%s", lugar);}
  125.                 fscanf(premiosinvend, lugar , 91, fichtxt);       //Lee la siguiente l&#65533;nea del fichero.
  126.                }
  127.        fclose(premiosinvend);
  128.   }}
  129.  
  130.  
  131. main(){
  132.   int intervnum, intervserie; /* longitud del intervalo */
  133.   int i;
  134.   struct fnum premios[TAM]; //matriz premios
  135.   struct registro resultado[TAM];
  136.   char f1[] = {"/home/alumnos/GI33_16/fichnumerosCompleto.dat"};
  137.   char f2[] = {"/home/alumnos/GI33_16/resul.dat"};
  138.   char f3[] = {"/home/alumnos/GI33_16/premios.txt.dat"};
  139.  FILE *result;
  140.  FILE *fich;
  141.  FILE *premiotxt;
  142.  
  143. inicializa_generador_aleatorios();
  144. inicializa_generador_aleatorios();
  145.   printf ("Produce un numero aleatorio de loteria: \n");
  146.  
  147.      /* Genera N aleatorios entre min y max */
  148.   intervnum = 9999 + 1;
  149.   intervserie = 9 + 1;
  150.  for (i=0; i< TAM; i++){
  151.     premios[i].numero = azar_numero(intervnum)%9999 +1;
  152.     premios[i].serie = azar_serie(intervserie);
  153.        printf ("\n Premio %d\t", i+1);
  154.        printf ("%d\t %d\n", premios[i].numero, premios[i].serie);}
  155.  
  156.  
  157.    //procedimiento para crear los ficheros y operar con ellos
  158.    buscar(premios, f1, f2, f3);
  159. result = fopen("result.dat", "r");
  160.    fread (&resultado[i], sizeof(struct registro), 1, result);
  161.        printf("\n%d \t%d \t%s", resultado[i].billete.numero, resultado[i].billete.serie, resultado[i].lugar);
  162.        fclose (result);
  163.  
  164.         leerficherotxt(f3);
  165.  
  166.         ponersinvender(f3);
  167.  
  168. } //main
  169.  
  170.  
muchas gracias por la ayuda ;)
6  Programación / Programación C/C++ / Re: Programa Loteria en: 15 Enero 2013, 11:06 am
Si te fijas bien mi duda es como hacer (o continuar) la función buscar, que consiste en comparar los resultados de los números "premiados" (result.dat) con los de un fichero que ya contiene numeros, series y lugares (este fichero es el dado por los profesores y se llama fichnumerosCompletos.dat).
7  Programación / Programación C/C++ / Re: Programa Loteria en: 15 Enero 2013, 00:40 am
Código
  1.  
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #define TAM 7
  5. //definicion de estructuras
  6.  
  7. struct fnum { int numero; int serie;}; //estructura del vector premios
  8. struct registro { struct fnum billete; char lugar[30];}registro;
  9.  
  10.  
  11.  
  12. /*definicion de funciones */
  13.  
  14. void inicializa_generador_aleatorios(){
  15.        /* Inicializa generador de n&#65533;meros aleatorios
  16.         E: (ninguna) S: (ninguna)*/
  17.        srand( time(NULL) );
  18.        }
  19.  
  20. int azar_numero( int tope ){
  21.        /* Funcion. Devuelve un entero al azar, menor que tope */
  22.        /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio
  23. / 1 <= valor devuelto <=tope */
  24.        return 1+(int)((float)tope*rand()/(RAND_MAX+1.0));
  25.        }
  26.  
  27. int azar_serie( int tope ){
  28.        /* Funcion. Devuelve un entero al azar, menor que tope */
  29.        /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio / 1 <= valor devuelto <=tope */
  30.        return 1+(int)((float)tope*rand()/(RAND_MAX+1.0));
  31.        }
  32.  
  33.  
  34. void buscar(struct fnum elegido, char lugar [30]){ //para buscar los numeros en fichnumeros
  35.        int seguir;
  36. FILE *fich;
  37.        seguir = 1;
  38.        while (seguir == 1){
  39.  
  40.                fich = fopen("fichnumerosCompleto.dat", "r");
  41.        if (fich == NULL)
  42.        printf("Error vacio\n");
  43.        else {
  44.  
  45.                fread(&registro, sizeof(struct registro), 1, fich);
  46.                // leerregistro(
  47.                while ((elegido.numero = registro.billete.numero)&&(elegido.serie = registro.billete.serie)) {
  48.                  //almacena lugar
  49.                        lugar[30] = *registro.lugar;
  50.                        seguir = 0;
  51.  
  52.                                }
  53.                //else leer registro( fread...\ esta funcion es la que no se seguir...
  54.  }
  55.                }
  56.        }
  57.  
  58.  
  59. main(){
  60.   int intervnum, intervserie; /* longitud del intervalo */
  61.   int i;
  62.   struct fnum premios[TAM]; //matriz premios
  63.   struct registro resultado[TAM];
  64.  FILE *result;
  65.  FILE *fich;
  66. inicializa_generador_aleatorios();
  67.   printf ("Produce un numero aleatorio de loteria: \n");
  68.  
  69.      /* Genera N aleatorios entre min y max y los imprime */
  70.   intervnum = 9999 + 1;
  71.   intervserie = 9 + 1;
  72.  for (i=0; i< TAM; i++){
  73.     premios[i].numero = azar_numero(intervnum)%9999 +1;
  74.     premios[i].serie = azar_serie(intervserie);
  75.        printf ("\n Premio %d\t", i+1);
  76.        printf ("%d\t %d\n", premios[i].numero, premios[i].serie);
  77.  
  78.     result = fopen("result.dat", "wr");
  79.        /* Apertura en modo lectura-escritura. result apunta a "result.dat"*/
  80.        if (result != NULL); { /*Comprobación*/
  81.           fwrite (&premios[i], sizeof(struct registro), 1, result);
  82.        resultado[i].billete.numero = premios[i].numero;
  83.        resultado[i].billete.serie= premios[i].serie;
  84.        buscar(premios[i], resultado[i].lugar);
  85.         // Escritura de los resultados junto a los lugares en que se vendio
  86.        fwrite (&resultado[i], sizeof(struct registro), 1, result);
  87.        fread (&resultado[i], sizeof(struct registro), 1, result);
  88.        printf("\n%d \t%d \t%s", resultado[i].billete.numero, resultado[i].billete.serie, resultado[i].lugar);
  89.        fclose (result);
  90. }
  91. }  }
  92.  
  93.        fich = fopen("fichnumerosCompleto.dat", "r");
  94.        if (fich == NULL)
  95.        printf("Error vacio\n");
  96.        else {
  97.        printf ("\t");
  98.         fread(&registro, sizeof(struct registro), 1, fich);
  99.                printf("\nNumero \tSerie \tLugar");
  100.           while((registro.billete.numero <= 10) && (registro.billete.serie <=3)){
  101.                printf("\n%d \t%d \t%s\n", registro.billete.numero, registro.billete.serie, registro.lugar);
  102.                fread(&registro, sizeof(struct registro), 1, fich);
  103.           }fclose(fich);
  104.        }
  105. } //main
  106.  

[MOD] usa la etiqueta GeSHi para colocar codigo, gracias.
8  Programación / Programación C/C++ / Programa Loteria en: 14 Enero 2013, 21:27 pm
Una empresa de loterías tiene almacenados los números que pone a la venta y los lugares
donde han sido vendidos en un fichero de registros (“fichnumeros.dat”), cuya estructura se
define posteriormente.  Cuando se realiza un sorteo se extraen TAM (>6) premios al azar y se
almacenan  en una matriz   de  tamaño  TAM llamada  premios,  cuya  estructura se  define  a
continuación. Los billetes tienen número y serie, estando  el número entre 0 y 9999 y la serie
entre 1 y 10
Queremos construir un programa en C que simule una lotería, más sencilla que una lotería real.
Las tareas que debe realizar son las siguientes:
• Análisis y diseño del problema.
• Obtener al azar los TAM premios, sabiendo que hay un Primer premio, un Segundo
premio, un Tercer premio, TAM/2 premios de cuarta categoría y el resto son premios
por el importe del billete (reintegros), y almacenarlos en una matriz  premios. Deben
utilizarse los subprogramas adecuados que proporcionan números al azar, para generar
la matriz premios. Los billetes premiados deben ser diferentes, teniendo en cuenta que
cada billete lleva número y serie.
• Debe escribir los resultados en un fichero  “result.dat”,  con la misma estructura de
registros  que  el  fichero  de  números,  pero  conteniendo  solamente  los  números
premiados.
• Debe escribir los resultados en un fichero de texto “premios.txt”,  en la forma que
muestra el caso de prueba, ordenándolos por cuantía del premio, (Primer premio,
Segundo premio…).
• Debe mostrar por pantalla el contenido del fichero de texto “premios.txt”, tal y como
está el fichero.
• Si el usuario  quiere,  debe mostrar por  pantalla  los premios que no se entregarán
porque en el fichero de números, en el campo “lugar” el valor es “Sin vender”.
Estructuras utilizadas
Estructura de los elementos del vector de premios
struct  fnum  { int numero; int serie;};
Estructura de los registros de “fichnumeros.dat”
struct  registro {struct fnum billete; char[30] lugar;}
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines