|
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: #include <stdlib.h> #include <stdio.h> #include <string.h> #define TAM 7 //definicion de estructuras struct fnum { int numero; int serie;}; //estructura del vector premios struct registro { struct fnum billete; char lugar[30];}registro; struct cadenacar{ char cad[16];}; /*definicion de funciones */ void inicializa_generador_aleatorios(){ /* Inicializa generador de n�meros aleatorios E: (ninguna) S: (ninguna)*/ srand( time(NULL) ); } int azar_numero( int tope ){ /* Funcion. Devuelve un entero al azar, menor que tope */ /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio / 1 <= valor devuelto <=tope */ return 1+(int)((float)tope*rand()/(RAND_MAX+1.0)); } int azar_serie( int tope ){ /* Funcion. Devuelve un entero al azar, menor que tope */ /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio / 1 <= valor devuelto <=tope */ return 1+(int)((float)tope*rand()/(RAND_MAX+1.0)); } void buscar(struct fnum elegido[TAM], char *fichero1, char *fichero2, char *fichero3) { //para buscar los numeros en fichnumeros struct cadenacar categoria[TAM]; char lugar[30]; int i, x; int seguir; int numero[TAM], serie[TAM]; struct registro registro; FILE *result; /* result apunta a "result.dat"*/ FILE *fich; // fich apunta a "fichnumerosCompletos.dat" FILE *premiotxt; // premiostxt apunta a "premios.txt" /* Apertura en modo lectura-escritura. */ fich = fopen("fichnumerosCompleto.dat", "r"); result = fopen("result.dat", "wr"); premiotxt = fopen("premios.txt", "w"); if (result != NULL && fich !=NULL && premiotxt !=NULL);{ /*Comprobación*/ seguir = 1; while (seguir == 1){ do { fread(®istro, sizeof(struct registro), 1, fich); for(i =0; i<TAM; i++){ if ((elegido[i].numero == registro.billete.numero) && (elegido[i].serie == registro.billete.serie)) { //almacena lugar fprintf(result, "%d\t %d\t %s\n",registro.billete.numero, registro.billete.serie,registro.lugar); numero[i] = registro.billete.numero; serie[i] = registro.billete.serie; lugar[i] = *registro.lugar; seguir = 0; } } }while (!feof(fich)); fclose(fich); fclose(result); } for (i = 0; i < TAM; i++){ if (i==0) strcpy(categoria[0].cad, "Primer premio:"); if (i==0) strcpy(categoria[0].cad, "Primer premio:"); if(i== 1) strcpy(categoria[1].cad, "Segundo premio:"); if (i==2) strcpy(categoria[2].cad, "Tercer premio:"); if ((i <= TAM/2)&&(i>2)){ strcpy(categoria[3+i].cad, "Cuarto premio:"); x=i;} else strcpy(categoria[1+x].cad, "Reintegro:"); } //los escribimos en premios.txt if ((numero[i] > 0 && numero[i] < 10000) && (serie[i] > 0 && serie[i] < 11)) fprintf(premiotxt,"%s\t%d\t%d\t%s\n",categoria[i].cad, numero[i], serie[i], lugar[i]); } fclose(premiotxt);//Cerramo el fichero txt } void leerficherotxt(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, lugar , 91, fichtxt); //Muestra datos por pantalla while ( !feof(premiotxt)){ //Mientras no ha llegado a la marca de fin de fichero lee linea a linea printf("%s", lugar); //Escribe una de las lineas en la pantalla. fscanf(premiotxt, lugar, 91, fichtxt); //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, lugar , 91, fichtxt); //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 b�squeda esta incluida en dato printf("%s", lugar);} fscanf(premiosinvend, lugar , 91, fichtxt); //Lee la siguiente l�nea del fichero. } fclose(premiosinvend); }} main(){ int intervnum, intervserie; /* longitud del intervalo */ int i; struct fnum premios[TAM]; //matriz premios struct registro resultado[TAM]; char f1[] = {"/home/alumnos/GI33_16/fichnumerosCompleto.dat"}; char f2[] = {"/home/alumnos/GI33_16/resul.dat"}; char f3[] = {"/home/alumnos/GI33_16/premios.txt.dat"}; FILE *result; FILE *fich; FILE *premiotxt; inicializa_generador_aleatorios(); inicializa_generador_aleatorios(); printf ("Produce un numero aleatorio de loteria: \n"); /* Genera N aleatorios entre min y max */ intervnum = 9999 + 1; intervserie = 9 + 1; for (i=0; i< TAM; i++){ premios[i].numero = azar_numero(intervnum)%9999 +1; premios[i].serie = azar_serie(intervserie); printf ("\n Premio %d\t", i+1); printf ("%d\t %d\n", premios[i].numero, premios[i].serie);} //procedimiento para crear los ficheros y operar con ellos buscar(premios, f1, f2, f3); result = fopen("result.dat", "r"); fread (&resultado[i], sizeof(struct registro), 1, result); printf("\n%d \t%d \t%s", resultado[i].billete.numero, resultado[i].billete.serie, resultado[i].lugar); fclose (result); leerficherotxt(f3); ponersinvender(f3); } //main
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
|
#include <stdlib.h> #include <stdio.h> #define TAM 7 //definicion de estructuras struct fnum { int numero; int serie;}; //estructura del vector premios struct registro { struct fnum billete; char lugar[30];}registro; /*definicion de funciones */ void inicializa_generador_aleatorios(){ /* Inicializa generador de n�meros aleatorios E: (ninguna) S: (ninguna)*/ srand( time(NULL) ); } int azar_numero( int tope ){ /* Funcion. Devuelve un entero al azar, menor que tope */ /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio / 1 <= valor devuelto <=tope */ return 1+(int)((float)tope*rand()/(RAND_MAX+1.0)); } int azar_serie( int tope ){ /* Funcion. Devuelve un entero al azar, menor que tope */ /* E: tope, maximo valor devuelto Valor devuelto: num aleatorio / 1 <= valor devuelto <=tope */ return 1+(int)((float)tope*rand()/(RAND_MAX+1.0)); } void buscar(struct fnum elegido, char lugar [30]){ //para buscar los numeros en fichnumeros int seguir; FILE *fich; seguir = 1; while (seguir == 1){ fich = fopen("fichnumerosCompleto.dat", "r"); if (fich == NULL) printf("Error vacio\n"); else { fread(®istro, sizeof(struct registro), 1, fich); // leerregistro( while ((elegido.numero = registro.billete.numero)&&(elegido.serie = registro.billete.serie)) { //almacena lugar lugar[30] = *registro.lugar; seguir = 0; } //else leer registro( fread...\ esta funcion es la que no se seguir... } } } main(){ int intervnum, intervserie; /* longitud del intervalo */ int i; struct fnum premios[TAM]; //matriz premios struct registro resultado[TAM]; FILE *result; FILE *fich; inicializa_generador_aleatorios(); printf ("Produce un numero aleatorio de loteria: \n"); /* Genera N aleatorios entre min y max y los imprime */ intervnum = 9999 + 1; intervserie = 9 + 1; for (i=0; i< TAM; i++){ premios[i].numero = azar_numero(intervnum)%9999 +1; premios[i].serie = azar_serie(intervserie); printf ("\n Premio %d\t", i+1); printf ("%d\t %d\n", premios[i].numero, premios[i].serie); result = fopen("result.dat", "wr"); /* Apertura en modo lectura-escritura. result apunta a "result.dat"*/ if (result != NULL); { /*Comprobación*/ fwrite (&premios[i], sizeof(struct registro), 1, result); resultado[i].billete.numero = premios[i].numero; resultado[i].billete.serie= premios[i].serie; buscar(premios[i], resultado[i].lugar); // Escritura de los resultados junto a los lugares en que se vendio fwrite (&resultado[i], sizeof(struct registro), 1, result); fread (&resultado[i], sizeof(struct registro), 1, result); printf("\n%d \t%d \t%s", resultado[i].billete.numero, resultado[i].billete.serie, resultado[i].lugar); fclose (result); } } } fich = fopen("fichnumerosCompleto.dat", "r"); if (fich == NULL) printf("Error vacio\n"); else { printf ("\t"); fread(®istro, sizeof(struct registro), 1, fich); printf("\nNumero \tSerie \tLugar"); while((registro.billete.numero <= 10) && (registro.billete.serie <=3)){ printf("\n%d \t%d \t%s\n", registro.billete.numero, registro.billete.serie, registro.lugar); fread(®istro, sizeof(struct registro), 1, fich); }fclose(fich); } } //main
[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;}
|
|
|
|
|
|
|