• Miércoles 24 de Abril de 2024, 11:06

Mostrar Mensajes

Esta sección te permite ver todos los posts escritos por este usuario. Ten en cuenta que sólo puedes ver los posts escritos en zonas a las que tienes acceso en este momento.


Temas - antlcn

Páginas: [1]
1
C++ Builder / Ahorcado cliente servidor TCP
« en: Lunes 16 de Abril de 2012, 09:37 »
Hola, estoy trabajando en el juego del ahorcado donde existe un servidor al que pueden conectarse varios clientes y jugar partidas individuales simultaneas gracias a la funcion select(). El caso es que al compilar "servidor.c" todo va bien pero lo ejecuto y me devuelve el siguiente error:


*** glibc detected *** ./servidor: corrupted double-linked list: 0x09310168 ***
======= Backtrace: =========
/lib/libc.so.6(+0x6c0c1)[0x17c0c1]
/lib/libc.so.6(+0x6d9f3)[0x17d9f3]
/lib/libc.so.6(cfree+0x6d)[0x180a1d]
/lib/libc.so.6(fclose+0x14a)[0x16c3da]
./servidor[0x8048ad2]
./servidor[0x80492d0]
/lib/libc.so.6(__libc_start_main+0xe7)[0x126ce7]
./servidor[0x8048931]
======= Memory map: ========
00110000-00267000 r-xp 00000000 07:00 21126      /lib/libc-2.12.1.so
00267000-00269000 r--p 00157000 07:00 21126      /lib/libc-2.12.1.so
00269000-0026a000 rw-p 00159000 07:00 21126      /lib/libc-2.12.1.so
0026a000-0026d000 rw-p 00000000 00:00 0
00381000-0039b000 r-xp 00000000 07:00 95         /lib/libgcc_s.so.1
0039b000-0039c000 r--p 00019000 07:00 95         /lib/libgcc_s.so.1
0039c000-0039d000 rw-p 0001a000 07:00 95         /lib/libgcc_s.so.1
003e8000-003e9000 r-xp 00000000 00:00 0          [vdso]
0081c000-00838000 r-xp 00000000 07:00 21110      /lib/ld-2.12.1.so
00838000-00839000 r--p 0001b000 07:00 21110      /lib/ld-2.12.1.so
00839000-0083a000 rw-p 0001c000 07:00 21110      /lib/ld-2.12.1.so
08048000-0804b000 r-xp 00000000 08:05 5213       /"RUTA FICHERO"/
0804b000-0804c000 r--p 00002000 08:05 5213        /"RUTA FICHERO"/
0804c000-0804d000 rw-p 00003000 08:05 5213        /"RUTA FICHERO"/
09310000-09331000 rw-p 00000000 00:00 0          [heap]
b7600000-b7621000 rw-p 00000000 00:00 0
b7621000-b7700000 ---p 00000000 00:00 0
b77b4000-b77b5000 rw-p 00000000 00:00 0
b77c9000-b77cb000 rw-p 00000000 00:00 0
bfada000-bfafb000 rw-p 00000000 00:00 0          [stack]
Abortado


Aquí dejo mi código:

Código: C
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <netdb.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8. #include <signal.h>
  9. #include <time.h>
  10. #include "funciones.c"
  11.  
  12.  
  13. void quitHandler(int sig);
  14.  
  15. int socketDes=-1; //socket del servidor
  16.  
  17. int main(void)
  18. {
  19.         /*---------------------------------------
  20.     Descriptor del socket y buffer de datos
  21.     ---------------------------------------*/
  22.  
  23.        
  24.         struct sockaddr_in sockname, from;
  25.         char buffer[200];
  26.         int from_len;
  27.  
  28.         struct hostent* host;
  29.  
  30.         /*-----------------
  31.     Se abre el socket
  32.     -----------------*/
  33.         socketDes = socket (AF_INET, SOCK_STREAM, 0);
  34.     if (socketDes == -1)
  35.     {
  36.       perror ("No se puede abrir el socket servidor");
  37.       exit(-1);
  38.     }
  39.  
  40.     /*------------------------------------------------------
  41.     Se rellenan los campos de la estructura con la IP del
  42.     servidor y el puerto del servicio que ofrecemos
  43.     ------------------------------------------------------*/
  44.  
  45.     sockname.sin_family = AF_INET;
  46.     sockname.sin_port = htons(2050);
  47.     sockname.sin_addr.s_addr = INADDR_ANY;
  48.  
  49.     if (bind (socketDes, (struct sockaddr*)&sockname, sizeof(sockname)) == -1)
  50.     {
  51.       perror("Error en la operacion bind");
  52.       close (socketDes);
  53.       exit(-1);
  54.     }
  55.  
  56.  
  57.     from_len = sizeof(from);
  58.  
  59.     if (listen(socketDes,1) == -1)
  60.     {
  61.       perror("Error en la operacion de listen");
  62.       close (socketDes);
  63.       exit(-1);
  64.     }
  65.  
  66.     signal(SIGINT, quitHandler);
  67.         signal(SIGTSTP, quitHandler);
  68.  
  69.     /*--------------------------------
  70.       Aceptar peticiones de clientes
  71.       -------------------------------*/
  72.     char **refranes;
  73.     int numRefranes;
  74.     struct cliente infoCli;
  75.  
  76.     int infoSelect;
  77.     int numClientesIn=0;
  78.  
  79.     int socketEntrada, newSocket;
  80.  
  81.     int i=0,j=0;
  82.  
  83.     char kword[30];
  84.     char bufferAux[200];
  85.     char *cadAux, *cadAux1;
  86.     int index=0, index1=0;
  87.     char letra;
  88.  
  89.     struct cliente auxCli;
  90.  
  91.     fd_set sockIn;
  92.     fd_set sockAux;
  93.  
  94.     FD_ZERO(&sockIn);
  95.     FD_ZERO(&sockAux);
  96.  
  97.     FD_SET(socketDes,&sockIn);
  98.  
  99.     refranes=extraeRefranes(&numRefranes);   //cargamos refranes desde fichero
  100.  
  101.  
  102.     while(1)   //bucle para el continuo analisis de peticiones de entrada
  103.     {
  104.         sockAux=sockIn;  //FD_COPY(&sockIn, &sockAux);
  105.  
  106.         infoSelect=select(FD_SETSIZE,&sockIn,NULL,NULL,NULL);
  107.         if(infoSelect==-1)
  108.         {
  109.                 perror("\nError en la funcion select()\n");
  110.                 exit(1);
  111.         }
  112.         else
  113.         {
  114.                 socketEntrada=buscarSocket(&sockIn);
  115.                 if(socketEntrada>=0)
  116.                 {
  117.                         if(recv(socketEntrada,buffer,200,0)==-1)
  118.                                 printf("\nError en la recepcion con -recv-\n");
  119.                         else
  120.                         {
  121.                                 i=0;
  122.                                         do
  123.                                         {
  124.                                                 kword[i]=buffer[i];
  125.                                                 i++;
  126.                                         }while(buffer[i]!=' ' && buffer[i]!='\0');
  127.                                         kword[i]='\0';
  128.  
  129.                                         if(strcmp(kword, "USUARIO")==0)  //se introdujo la clave USUARIO
  130.                                         {
  131.                                                 cadAux=buffer+8;
  132.                                                 auxCli=buscaClienteNombre(cadAux);
  133.  
  134.                                                 if(auxCli.registrado!=1)
  135.                                                 {
  136.                                                         strcpy(buffer,"-Err. Usuario incorrecto");
  137.                                                         if(send(socketEntrada,buffer,200,0)==-1)
  138.                                                                 perror("\nSe produjo un erro al enviar\n");
  139.                                                 }
  140.                                                 else
  141.                                                 {
  142.                                                         if(auxCli.loggeado!=1)
  143.                                                         {
  144.                                                                 auxCli.loggeado=1;
  145.                                                                 auxCli.numSocket= socketEntrada;
  146.                                                                 modificarCliente(auxCli);
  147.                                                         }
  148.  
  149.                                                         strcpy(buffer,"-Ok. Usuario correcto");
  150.                                                         if(send(socketEntrada,buffer,200,0)==-1)
  151.                                                                 perror("\nSe produjo un erro al enviar\n");
  152.                                                 }
  153.                                                
  154.                                         }//fin opcion USUARIO
  155.  
  156.                                         if(strcmp(kword,"PASSWORD")==0)  //se introdujo la clav PASSWORD
  157.                                         {
  158.                                                 cadAux=buffer+9; //esta es la contraseña
  159.  
  160.                                                 auxCli=buscaCliente(socketEntrada);
  161.                                                 //puede ser NULL??????????????????????
  162.                                                 if(auxCli.loggeado==1 && (strcmp(auxCli.passUser,cadAux)==0))
  163.                                                 {
  164.                                                         strcpy(buffer, "+Ok. Usuario validado");
  165.                                             if(send(socketEntrada, buffer, 200, 0) == -1)
  166.                                                             perror("Error en el envio");
  167.                                                        
  168.                                                         modificarCliente(auxCli);  //se incluye la informacion en el fichero
  169.                                                 }
  170.                                                 else
  171.                                                 {
  172.                                                         strcpy(buffer, "-Err. Error en la validacion");
  173.                                             if(send(socketEntrada, buffer, 200, 0) == -1)
  174.                                                             perror("Error en el envio");
  175.                                                 }
  176.  
  177.                                                
  178.                                         }//fin opcion PASSWORD
  179.  
  180.  
  181.                                         if(strcmp(kword,"REGISTRO")==0)  //se introdujo la clave REGISTRO
  182.                                         {
  183.                                                 for(i=0;i<=strlen(buffer);i++)
  184.                                                 {
  185.                                                         if(buffer[i]=='-' && buffer[i+1]=='u')
  186.                                                         {
  187.                                                                 index=i+3;
  188.                                                                 cadAux=buffer+index; //aqui esta el usuario
  189.                                                         }
  190.                                                         if(buffer[i]=='-' && buffer[i+1]=='p')
  191.                                                         {
  192.                                                                 cadAux1=buffer+(i+3); //aqui la contraseña
  193.                                                                 index1=i;
  194.                                                         }
  195.                                                 }
  196.                                                 cadAux[index1-index-1]='\0';
  197.  
  198.                                                 auxCli=buscaClienteNombre(cadAux);
  199.  
  200.                                                 if(auxCli.registrado!=1)
  201.                                                 {
  202.                                                         auxCli.numSocket=0;
  203.                                                         auxCli.jugando=0;
  204.                                                         auxCli.registrado=1;
  205.                                                         auxCli.loggeado=0;
  206.                                                         auxCli.autenticado=0;
  207.                                                         strcpy(auxCli.nombreUser,cadAux);
  208.                                                         strcpy(auxCli.passUser,cadAux1);
  209.                                                         auxCli.puntuacionPartida=0;
  210.                                                         auxCli.puntuacionTotal=0;
  211.                                                         auxCli.numIntentos=0;
  212.                                                         auxCli.numeroRefran=-1;
  213.                                                         auxCli.frasesAcertadas=0;
  214.                                                         auxCli.frasesFalladas=0;
  215.                                                         auxCli.modoJuego=-1;
  216.  
  217.                                                         introduceCliente(auxCli);
  218.  
  219.                                                         strcpy(buffer,"+Ok. Usuario registrado");
  220.                                                         if(send(socketEntrada,buffer,200,0)==-1)
  221.                                                                 perror("Error envio confirmacion registro");
  222.                                                 }
  223.                                                 else
  224.                                                 {
  225.                                                         strcpy(buffer,"-Err. Usuario ya existe");
  226.                                                         if(send(socketEntrada,buffer,200,0)==-1)
  227.                                                                 perror("Error envio respuesta registro");
  228.                                                 }
  229.                                                
  230.                                         } //fin opcion registro
  231.  
  232.                                         if(strcmp(kword,"VOCAL")==0)
  233.                                         {
  234.                                                 auxCli=buscaCliente(socketEntrada);
  235.  
  236.                                                 letra=buffer[6];
  237.                                                 if(letra=='a' || letra=='e' || letra=='i' || letra=='o' || letra=='u')
  238.                                                 {
  239.                                                         if(auxCli.modoJuego==0)
  240.                                                         {
  241.                                                                 if(compruebaLetra(refranes[auxCli.numeroRefran], auxCli.frasePartida, letra)==1)
  242.                                                                 {
  243.                                                                         strcpy(buffer,"+Ok. Existe la vocal ---> ");
  244.                                                                         strcat(buffer,auxCli.frasePartida);
  245.                                                                         if(send(socketEntrada,buffer,200,0)==-1)
  246.                                                                                 perror("\nError al enviar confirmacion vocal\n");
  247.                                                                 }
  248.                                                                 else
  249.                                                                 {
  250.                                                                         strcpy(buffer,"-Err. No existe la vocal ---> ");
  251.                                                                         strcat(buffer,auxCli.frasePartida);
  252.                                                                         if(send(socketEntrada,buffer,200,0)==-1)
  253.                                                                                 perror("\nError al enviar confirmacion vocal\n");
  254.                                                                 }
  255.  
  256.                                                                 auxCli.numIntentos++;
  257.                                                         }
  258.                                                 }
  259.                                                 else
  260.                                                 {
  261.                                                         strcpy(buffer,"-Err. Mensaje invalido");
  262.                                                         if(send(socketEntrada,buffer,200,0)==-1)
  263.                                                                 perror("\nError al enviar mensaje error\n");
  264.                                                 }
  265.  
  266.                                                
  267.  
  268.                                         } //fin opcion VOCAL
  269.  
  270.  
  271.  
  272.                                         if(strcmp(kword,"CONSONANTE")==0)
  273.                                         {
  274.                                                 auxCli=buscaCliente(socketEntrada);
  275.  
  276.                                                 letra=buffer[11];
  277.                                                 if(letra!='a' && letra!='e' && letra!='i' && letra!='o' && letra!='u')
  278.                                                 {
  279.                                                         if(auxCli.modoJuego==0)
  280.                                                         {
  281.                                                                 if(compruebaLetra(refranes[auxCli.numeroRefran], auxCli.frasePartida, letra)==1)
  282.                                                                 {
  283.                                                                         strcpy(buffer,"+Ok. Existe la consonante ---> ");
  284.                                                                         strcat(buffer,auxCli.frasePartida);
  285.                                                                         if(send(socketEntrada,buffer,200,0)==-1)
  286.                                                                                 perror("\nError al enviar confirmacion consonante\n");
  287.                                                                 }
  288.                                                                 else
  289.                                                                 {
  290.                                                                         strcpy(buffer,"-Err. No existe la consonante ---> ");
  291.                                                                         strcat(buffer,auxCli.frasePartida);
  292.                                                                         if(send(socketEntrada,buffer,200,0)==-1)
  293.                                                                                 perror("\nError al enviar confirmacion consonante\n");
  294.                                                                 }
  295.  
  296.                                                                 auxCli.numIntentos++;
  297.                                                         }
  298.                                                 }
  299.                                                 else
  300.                                                 {
  301.                                                         strcpy(buffer,"-Err. Mensaje invalido");
  302.                                                         if(send(socketEntrada,buffer,200,0)==-1)
  303.                                                                 perror("\nError al enviar mensaje error\n");
  304.                                                 }
  305.                                                
  306.  
  307.                                         } //fin opcion CONSONANTE
  308.  
  309.  
  310.                                         if(strcmp(kword,"RESOLVER")==0)
  311.                                         {
  312.                                                 auxCli=buscaCliente(socketEntrada);
  313.  
  314.                                                 if(auxCli.modoJuego==0)
  315.                                                 {
  316.                                                         if(strcmp(buffer+9,refranes[auxCli.numeroRefran])==0)
  317.                                                         {
  318.                                                                 if(auxCli.numIntentos<5)
  319.                                                                         auxCli.puntuacionPartida=150;
  320.                                                                 if(auxCli.numIntentos>=5 && auxCli.numIntentos<=8)
  321.                                                                         auxCli.puntuacionPartida=100;
  322.                                                                 if(auxCli.numIntentos>=9 && auxCli.numIntentos<=11)
  323.                                                                         auxCli.puntuacionPartida=70;
  324.                                                                 if(auxCli.numIntentos>=12 && auxCli.numIntentos<=15)
  325.                                                                         auxCli.puntuacionPartida=50;
  326.                                                                 if(auxCli.numIntentos>15)
  327.                                                                         auxCli.puntuacionPartida=0;
  328.  
  329.                                                                 auxCli.frasesAcertadas++;
  330.                                                                 auxCli.puntuacionTotal+=auxCli.puntuacionPartida;
  331.  
  332.                                                                 sprintf(bufferAux,"+Ok. Enhorabuena\n\n Puntuacion en esta partida: %d\nPuntuacion total: %d\nIntentos realizados: %d\nFrases acertadas: %d\nFrases fallidas: %d",auxCli.puntuacionPartida,auxCli.puntuacionTotal,auxCli.numIntentos,auxCli.frasesAcertadas,auxCli.frasesFalladas);
  333.                                                                 auxCli.puntuacionPartida=0;
  334.  
  335.                                                                 if(send(socketEntrada,bufferAux,200,0)==-1)
  336.                                                                         perror("\nError al enviar estadisticas\n");
  337.                                                         }
  338.                                                         else
  339.                                                         {
  340.                                                                 auxCli.frasesFalladas++;
  341.                                                                 sprintf(bufferAux,"-Err. Mejor suerte la proxima vez\n\n Puntuacion en esta partida: %d\nPuntuacion total: %d\nIntentos realizados: %d\nFrases acertadas: %d\nFrases fallidas: %d",auxCli.puntuacionPartida,auxCli.puntuacionTotal,auxCli.numIntentos,auxCli.frasesAcertadas,auxCli.frasesFalladas);
  342.                                                                 auxCli.puntuacionPartida=0;
  343.  
  344.                                                                 if(send(socketEntrada,bufferAux,200,0)==-1)
  345.                                                                         perror("\nError al enviar estadisticas\n");
  346.  
  347.                                                                 //reiniciamos la informacion del jugador
  348.                                                                 auxCli.jugando=0;
  349.                                                                 auxCli.modoJuego=-1;
  350.                                                                 auxCli.puntuacionPartida=0;
  351.                                                                 strcpy(auxCli.frasePartida,"");
  352.                                                                 auxCli.numIntentos=0;
  353.                                                                 auxCli.numeroRefran=-1;
  354.  
  355.                                                         }
  356.                                                 }
  357.                                                
  358.  
  359.                                         } //fin opcion RESOLVER
  360.  
  361.  
  362.                                         if(strcmp(kword,"PARTIDA-INDIVIDUAL")==0)
  363.                                         {
  364.                                                 auxCli=buscaCliente(socketEntrada);
  365.  
  366.                                                 if(auxCli.loggeado==1 && auxCli.registrado==1 && auxCli.autenticado==1)
  367.                                                 {
  368.                                                         if(auxCli.jugando==0)
  369.                                                         {
  370.                                                                 auxCli.jugando=1;
  371.                                                                 auxCli.modoJuego=0;
  372.  
  373.                                                                 srand(time(NULL));
  374.                                                                 auxCli.numeroRefran=rand()%numRefranes;
  375.  
  376.                                                                 strcpy(buffer,"");
  377.                                                                 j=0;
  378.                                                                 for(i=0;i<strlen(refranes[auxCli.numeroRefran]);i++)
  379.                                                                 {
  380.                                                                         switch(refranes[auxCli.numeroRefran][i])
  381.                                                                         {
  382.                                                                                 case ',':
  383.                                                                                         buffer[i]=',';
  384.                                                                                         break;
  385.                                                                                 case ' ':
  386.                                                                                         buffer[i]=' ';
  387.                                                                                         break;
  388.                                                                                 case '.':
  389.                                                                                         buffer[i]='.';
  390.                                                                                 default:
  391.                                                                                         buffer[i]='-';
  392.                                                                                         break;
  393.                                                                         }
  394.                                                                 }
  395.                                                                 buffer[i]='\0';
  396.                                                                 strcpy(auxCli.frasePartida,buffer);
  397.  
  398.                                                                 if (send(socketEntrada, buffer, 200, 0) == -1)
  399.                                                                         perror("\nError envio refran oculto\n");
  400.                                                         }
  401.                                                         else
  402.                                                         {
  403.                                                                 strcpy(buffer, "-Err. Ya tiene una partida en curso");
  404.                                                              if(send(socketEntrada, buffer, 200, 0) == -1)
  405.                                                                         perror("Error en el envio");
  406.                                                         }
  407.                                                 }
  408.                                                 else
  409.                                                 {
  410.                                                         strcpy(buffer, "-Err. Debe iniciar sesion antes de empezar");
  411.                                                     if(send(socketEntrada, buffer, 200, 0) == -1)
  412.                                                                 perror("\nError en el envio fallo partida nueva\n");;
  413.                                                 }
  414.                                                
  415.  
  416.                                         } //fin opcion PARTIDA-INDIVIDUAL
  417.  
  418.  
  419.                                         if(strcmp(kword,"PARTIDA-GRUPO")==0)
  420.                                         {
  421.                                                 //CODIGO PARA PARTIDA COLECTIVA
  422.                                         }
  423.  
  424.                                         if(strcmp(kword,"SALIR")==0)
  425.                                         {
  426.                                                 strcpy(buffer,"¡Hasta otra!");
  427.                                                 if(send(socketEntrada,buffer,200,0)==-1)
  428.                                                         perror("\nError en el envio de mensaje salida\n");
  429.                                                 close(socketEntrada);
  430.                                                 FD_CLR(socketEntrada,&sockAux);
  431.                                                 auxCli=buscaCliente(socketEntrada);
  432.  
  433.                                                 if(auxCli.registrado==1)
  434.                                                 {
  435.                                                         auxCli.numSocket=0;
  436.                                                         auxCli.jugando=0;
  437.                                                         auxCli.loggeado=0;
  438.                                                         auxCli.autenticado=0;
  439.                                                         auxCli.modoJuego=-1;
  440.                                                         strcpy(auxCli.frasePartida,"");
  441.                                                         auxCli.numeroRefran=-1;
  442.                                                         auxCli.frasesFalladas=0;
  443.                                                         auxCli.frasesAcertadas=0;
  444.                                                         auxCli.puntuacionPartida=0;
  445.                                                         auxCli.numIntentos=0;
  446.                                                 }
  447.  
  448.                                                 numClientesIn--;
  449.  
  450.                                         } //fin opcion SALIR
  451.  
  452.                         }//fin else de recepcion de mensaje
  453.  
  454.                         sockIn=sockAux;//FD_COPY(&sockAux,&sockIn);
  455.  
  456.                 }//fin if de existencia de socketEntrada
  457.                 else  //si no esta en el conjunto de sockets
  458.                 {
  459.                         if((newSocket=accept(socketDes,(struct sockaddr*)&from, &from_len))==-1)
  460.                         {
  461.                                 printf("\nError aceptando peticion de conexion\n");
  462.                                 exit(1);
  463.                         }
  464.                         else
  465.                                 numClientesIn++;
  466.                         if(numClientesIn>50)
  467.                         {
  468.                                 strcpy(buffer,"\n-Err. No se aceptan mas conexiones\n");
  469.                                 if(send(newSocket,buffer,200,0)==-1)
  470.                                         perror("\nError envio negacion conexion\n");
  471.                                 close(newSocket);
  472.                         }
  473.                         else
  474.                         {
  475.                                 printf("\n+Ok. Aceptada una nueva conexion, usuario nº %d",numClientesIn);
  476.  
  477.                                 auxCli.numSocket=newSocket;
  478.                                 auxCli.jugando=0;
  479.                                 auxCli.registrado=0;
  480.                                 auxCli.loggeado=0;
  481.                                 auxCli.autenticado=0;
  482.                                 auxCli.modoJuego=-1;
  483.                                 strcpy(auxCli.nombreUser,"");
  484.                                 strcpy(auxCli.passUser,"");
  485.                                 auxCli.puntuacionPartida=0;
  486.                                 auxCli.puntuacionTotal=0;
  487.                                 strcpy(auxCli.frasePartida,"");
  488.                                 auxCli.numIntentos=0;
  489.                                 auxCli.numeroRefran=-1;
  490.                                 auxCli.frasesAcertadas=0;
  491.                                 auxCli.frasesFalladas=0;
  492.  
  493.                                 introduceCliente(auxCli);
  494.                         }
  495.  
  496.                         sockIn=sockAux;//FD_COPY(&sockAux,&sockIn);
  497.  
  498.                         if(numClientesIn<50)
  499.                                 FD_SET(newSocket,&sockIn);
  500.                         sockAux=sockIn;//FD_COPY(&sockIn,&sockAux);
  501.                 }
  502.         }
  503.     }
  504.     return 0;
  505.  
  506. }
  507.  
  508. void quitHandler (int sig)
  509. {
  510.   close(socketDes);
  511.   printf("\nServidor terminado\n");
  512.   exit(0);
  513. }
  514.  




Gracias de antemano.

Un saludo!

2
C/C++ / Clase matriz con plantillas
« en: Viernes 5 de Agosto de 2011, 17:44 »
Hola, tengo un programa escrito en C++ que define una clase matriz con plantillas esta todo en un .h con las funciones inline, y al compilar me da errores que no se de que son. Una ayudita por favor!.

Código: C++
  1. #ifndef _Matrix_H_
  2. #define _Matrix_H_
  3. #include <cassert>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7. namespace storage{
  8.     template<class Type>
  9.         class Matrix
  10.         {
  11.             public:
  12.                 /* constructor vacio
  13.                  */
  14.                 inline Matrix();
  15.                 /* constructor copia
  16.                  */
  17.                 inline Matrix(const Matrix &M);
  18.                 /* constructor parametrizado
  19.                  */
  20.                 inline Matrix(unsigned int nRows, unsigned int nCols);
  21.                 /* destructor
  22.                  */
  23.                 inline ~Matrix();
  24.                 /* redimensionar la matriz
  25.                  */            
  26.                 inline void resize(unsigned int nRows, unsigned int nCols);
  27.                 /* indica el numero de filas
  28.                 */
  29.                 unsigned int getNRows() { return _nRows;}
  30.                 /* indica el numero de columnas
  31.                  */
  32.                 unsigned int getNCols() { return _nCols;}
  33.                 /* retorna el valor indicado por las variables
  34.                  */
  35.                 inline Type & get(unsigned int r,unsigned int c);
  36.                 /* hace que la matriz sea la indentidad
  37.                  */
  38.                 inline void setIdentity();
  39.                 /* operador de asignacion
  40.                  */
  41.                 inline Matrix & operator=(const Matrix &M);
  42.                 /* realiza la suma de dos matrices
  43.                  */
  44.                 inline Matrix operator+(const Matrix &M);
  45.                
  46.                
  47.         private:
  48.             Type **_data;
  49.             unsigned int _nRows;
  50.             unsigned int _nCols;
  51.         };
  52.  
  53.        
  54.  
  55. //////////////////////////
  56. //
  57. //////////////////////////
  58. template<class Type>
  59. Matrix<Type>::Matrix()
  60. {
  61.   _data=NULL;
  62.   _nRows=0;
  63.   _nCols=0;
  64. }
  65.  
  66. //////////////////////////
  67. //
  68. //////////////////////////
  69. template<class Type>
  70. Matrix<Type>::Matrix(const Matrix &M)
  71. {
  72.   int i=0,j=0;
  73.   _data=NULL;
  74.   resize(M._nRows, M._nCols);
  75.  
  76.   for(i=0;i<_nRows;i++)
  77.   {
  78.     for(j=0;j<_nCols;j++)
  79.     {
  80.       _data[i][j]=M._data[i][j];
  81.     }
  82.   }
  83. }
  84.  
  85. //////////////////////////
  86. //
  87. //////////////////////////
  88. template<class Type>
  89. Matrix<Type>::Matrix(unsigned int nRows, unsigned int nCols)
  90. {
  91.   _data=NULL;
  92.   resize(nRows, nCols);
  93. }
  94.  
  95.  
  96. //////////////////////////
  97. //
  98. //////////////////////////
  99. template<class Type>
  100. Matrix<Type>::~Matrix()
  101. {
  102.   int i;
  103.   if(_data!=NULL){
  104.     for(i=0;i<_nRows;i++){
  105.       delete []_data[i];
  106.     }
  107.     delete []_data;
  108.   }
  109. }
  110.  
  111. //////////////////////////
  112. //
  113. //////////////////////////
  114. template<class Type>
  115. void Matrix<Type>::resize(unsigned int nRows, unsigned int nCols)
  116. {
  117.   int i;
  118.   if(_data!=NULL){
  119.     for(i=0;i<nRows;i++){
  120.       delete []_data[i];
  121.     }
  122.     delete []_data;
  123.   }
  124.  
  125.   _nRows=nRows;
  126.   _nCols=nCols;
  127.  
  128.   _data=NULL;
  129.     _data=new Type *[_nRows];
  130.     for(i=0;i<_nRows;i++)
  131.       _data[i]=new Type[_nCols];
  132.   }
  133. }
  134.  
  135. //////////////////////////
  136. //
  137. //////////////////////////
  138. template<class Type>
  139. Type & Matrix<Type>::get(unsigned int r, unsigned int c)
  140. {
  141.   assert(0<r<_nRows);
  142.   assert(0<r<_nCols);
  143.   return _data[r][c];
  144. }
  145.  
  146. //////////////////////////
  147. //
  148. //////////////////////////
  149. template<class Type>
  150. void Matrix<Type>::setIdentity()
  151. {
  152.   int i,j;
  153.   for(i=0;i<_nRows;i++){
  154.     for(j=0;j<_nCols;j++){
  155.       if(i==j)
  156.     _data[i][j]=1;
  157.       else
  158.     _data[i][j]=0;
  159.     }
  160.   }
  161. }
  162.  
  163. //////////////////////////
  164. //
  165. //////////////////////////
  166. template<class Type>
  167. Matrix<Type> & Matrix<Type>::operator=(const Matrix &M)
  168. {
  169.   int i,j;
  170.   if(_nRows==M._nRows && _nCols==M._nCols)
  171.   for(i=0;i<_nRows;i++)
  172.     for(j=0;j<_nCols;j++)
  173.       _data[i][j]=M._data[i][j];
  174.   return *this;
  175. }
  176.  
  177. //////////////////////////
  178. //
  179. //////////////////////////
  180. template<class Type>
  181. Matrix<Type> Matrix<Type>::operator+(const Matrix &M)
  182. {
  183.   assert(_nRows==M._nRows && _nCols==M._nCols);
  184.   Matrix<Type> aux(M._nRows, M._nCols);
  185.   int i,j;
  186.   for(i=0;i<_nRows;i++){
  187.     for(j=0;j<_nCols;j++){
  188.       aux._data[i][j]=_data[i][j]+M._data[i][j];
  189.     }
  190.   }
  191.   return aux;//no se si esto se puede hacer
  192. }
  193. };
  194.  
  195.  
  196. #endif
  197.  


Este es el main.cpp para probrarlo:

Código: C++
  1. #include <matrix.h>
  2. #include <iostream>
  3. using namespace std;
  4. using namespace storage;
  5.  
  6. //template Function that prints a matrix
  7.  
  8. template<class Type>
  9. void print(Matrix<Type> &M)
  10. {
  11.   for(unsigned int i=0;i<M.getNRows();i++){
  12.   for(unsigned int j=0;j<M.getNCols();j++)
  13.   cout<<M.get(i,j)<< " ";
  14.   cout<<endl;
  15.   }
  16.  cout<<endl;
  17. }
  18.  
  19. int main(int argc,char **argv)
  20. {
  21.   Matrix<float> M;
  22.   M.resize(10,10);
  23.   M.setIdentity();
  24.   print(M);
  25.   Matrix<float> M2(M);
  26.   print(M2);
  27.   Matrix<float> M3(10,10);
  28.   M3=M+M2;
  29.   print(M3);
  30.   //check the result
  31.   for(unsigned int i=0;i<M3.getNRows();i++){
  32.   for(unsigned int j=0;j<M.getNCols();j++)
  33.   if (i!=j)
  34.   assert(M3.get(i,j)==0);
  35.   else assert(M3.get(i,j)==2);
  36.   }
  37.   cout<<"Perfect"<<endl;
  38. }

3
C/C++ / Clase matriz "violación de segmento"
« en: Viernes 28 de Enero de 2011, 12:37 »
Hola, estoy haciendo una clase matriz con sus constructores, operadores, etc y me da un fallo de segmentación tras la comprobación "Ok4" del main, les adjunto el codigo:


main.cpp:
Código: C++
  1. #include <matrix.h>
  2. #include <iostream>
  3. using namespace std;
  4. using namespace storage;
  5.  
  6. //template Function that prints a matrix
  7.  
  8. template<class Type>
  9. void print(Matriz<Type> &M)
  10. {
  11. for(unsigned int i=0;i<M.getNRows();i++){
  12. for(unsigned int j=0;j<M.getNCols();j++)
  13. cout<<M.get(i,j)<< " ";
  14. cout<<endl;
  15. }
  16. }
  17.  
  18. int main(int argc,char **argv)
  19. {
  20. Matriz<float> M;
  21. M.resize(10,10);
  22. cout<<"ok1"<<endl;
  23. M.setIdentity();
  24. cout<<"ok2"<<endl;
  25. print(M);
  26. cout<<"ok3"<<endl;
  27. Matriz<float> M2(M);
  28. print(M2);
  29. cout<<"ok4"<<endl;
  30. Matriz<float> M3(10,10);
  31. M3=M+M2;
  32. cout<<"ok5"<<endl;
  33. print(M3);
  34. cout<<"ok6"<<endl;
  35. //check the result
  36. for(unsigned int i=0;i<M3.getNRows();i++){
  37. for(unsigned int j=0;j<M.getNCols();j++)
  38. if (i!=j)
  39. assert(M3.get(i,j)==0);
  40. else assert(M3.get(i,j)==2);
  41. }
  42. cout<<"Perfect"<<endl;
  43. }
  44.  
  45.  



matrix.h:
Código: C++
  1. #ifndef _Matrix_H_
  2. #define _Matrix_H_
  3. #include <cassert>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7. namespace storage{
  8.     template<class Type>
  9.         class Matriz
  10.         {
  11.             public:
  12.                 /* constructor vacio
  13.                  */
  14.                 inline Matriz();
  15.                 /* constructor copia
  16.                  */
  17.                 inline Matriz(const Matriz &M);
  18.                 /* constructor parametrizado
  19.                  */
  20.                 inline Matriz(unsigned int nRows, unsigned int nCols);
  21.                 /* redimensionar la matriz
  22.                  */
  23.                 inline void resize(unsigned int nRows, unsigned int nCols);
  24.                 /* indica el numero de filas
  25.                 */
  26.                 unsigned int getNRows() { return _nRows;}
  27.                 /* indica el numero de columnas
  28.                  */
  29.                 unsigned int getNCols() { return _nCols;}
  30.                 /* retorna el valor indicado por las variables
  31.                  */
  32.                 inline Type & get(unsigned int r,unsigned int c);
  33.                 /* hace que la matriz sea la indentidad
  34.                  */
  35.                 inline void setIdentity();
  36.                 /* operador de asignacion
  37.                  */
  38.                 inline Matriz & operator=(const Matriz &M);
  39.                 /* realiza la suma de dos matrices
  40.                  */
  41.                 inline Matriz & operator+(const Matriz &M);
  42.                 /* destructor
  43.                  */
  44.                 inline ~Matriz();
  45.                
  46.         private:
  47.             Type **_data;
  48.             unsigned int _nRows;
  49.             unsigned int _nCols;
  50.         };
  51.  
  52.        
  53.  
  54. //////////////////////////
  55. //
  56. //////////////////////////
  57. template<class Type>
  58. Matriz<Type>::Matriz()
  59. {
  60.   _data=NULL;
  61.   _nRows=0;
  62.   _nCols=0;
  63. }
  64.  
  65. //////////////////////////
  66. //
  67. //////////////////////////
  68. template<class Type>
  69. Matriz<Type>::Matriz(const Matriz &M)
  70. {
  71.   int i,j;
  72.   _nRows=M._nRows;
  73.   _nCols=M._nCols;
  74.   _data= new Type*[_nRows];
  75.   for(i=0;i<_nRows;i++){
  76.      _data[i]=new Type[_nCols];
  77.   }
  78.   for(i=0;i<_nRows;i++){
  79.     for(j=0;j<_nCols;j++){
  80.       _data[i][j]=M._data[i][j];
  81.     }
  82.   }
  83. }
  84.  
  85. //////////////////////////
  86. //
  87. //////////////////////////
  88. template<class Type>
  89. Matriz<Type>::Matriz(unsigned int nRows, unsigned int nCols)
  90. {
  91.   int i;
  92.   _nRows=nRows;
  93.   _nCols=nCols;
  94.   if(_data==NULL){
  95.   _data= new Type*[_nRows];
  96.   for(i=0;i<_nRows;i++){
  97.      _data[i]=new Type[_nCols];
  98.   }
  99.   }
  100. }
  101.  
  102. //////////////////////////
  103. //
  104. //////////////////////////
  105. template<class Type>
  106. void Matriz<Type>::resize(unsigned int nRows, unsigned int nCols)
  107. {
  108.   int i;
  109.   if(_data!=NULL){
  110.     for(i=0;i<nRows;i++){
  111.       delete []_data[i];
  112.     }
  113.     delete []_data;
  114.   }
  115.   Matriz(nRows, nCols);
  116. }
  117.  
  118. //////////////////////////
  119. //
  120. //////////////////////////
  121. template<class Type>
  122. Type & Matriz<Type>::get(unsigned int r, unsigned int c)
  123. {
  124.   return _data[r][c];
  125. }
  126.  
  127. //////////////////////////
  128. //
  129. //////////////////////////
  130. template<class Type>
  131. void Matriz<Type>::setIdentity()
  132. {
  133.   int i,j;
  134.   for(i=0;i<_nRows;i++){
  135.     for(j=0;j<_nCols;j++){
  136.       if(i==j)
  137.     _data[i][j]=1;
  138.       else
  139.     _data[i][j]=0;
  140.     }
  141.   }
  142. }
  143.  
  144. //////////////////////////
  145. //
  146. //////////////////////////
  147. template<class Type>
  148. Matriz<Type> & Matriz<Type>::operator=(const Matriz &M)
  149. {
  150.   int i,j;
  151.   if(_data==NULL)
  152.     Matriz(M._nRows, M._nCols);
  153.   for(i=0;i<_nRows;i++){
  154.     for(j=0;j<_nCols;j++){
  155.       _data[i][j]=M._data[i][j];
  156.     }
  157.   }
  158.   return *this;
  159. }
  160.  
  161. //////////////////////////
  162. //
  163. //////////////////////////
  164. template<class Type>
  165. Matriz<Type> & Matriz<Type>::operator+(const Matriz &M)
  166. {
  167.   int i,j;
  168.   if(_data==NULL)
  169.     Matriz(M._nRows, M._nCols);
  170.   for(i=0;i<_nRows;i++){
  171.     for(j=0;j<_nCols;j++){
  172.       _data[i][j]=_data[i][j]+M._data[i][j];
  173.     }
  174.   }
  175.   return *this;
  176. }
  177.  
  178. //////////////////////////
  179. //
  180. //////////////////////////
  181. template<class Type>
  182. Matriz<Type>::~Matriz()
  183. {
  184.   int i;
  185.   if(_data!=NULL){
  186.     for(i=0;i<_nRows;i++){
  187.       delete []_data[i];
  188.     }
  189.     delete []_data;
  190.   }
  191. }
  192. };
  193.  
  194. #endif
  195.  
  196.  


gracias de antemano.

4
C/C++ / Suma de elementos de vector con plantillas
« en: Jueves 27 de Enero de 2011, 17:44 »
hola, tengo un problema con un ejemplo de programa en C++ que suma los elementos de un vector utilizando una clase plantilla, me da un error en la linea 21 de el archivo suma.h, a continuación pongo el código:

main.cpp:
Código: C++
  1. #include<iostream>
  2. #include<suma.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. using namespace values;
  6.  
  7. int
  8. main(void)
  9. {
  10.     Suma<int> S;
  11.     int *V, nElementos;
  12.     cout<<"Introduce el numero de elementos del vector: "<<endl;
  13.     cin>>nElementos;
  14.     V=(int *)malloc(nElementos*sizeof(int));
  15.     S.sumar(V, nElementos);
  16.     cout<<S.getResult()<<endl;
  17.     free(V);
  18.     return 0;
  19. }
  20.  



suma.h:
Código: C++
  1. #ifndef _SUMA_H_
  2. #define _SUMA_H_
  3.  
  4. namespace values{
  5.     /** Brief esta clase realiza la suma de un vector
  6.     */
  7.     template<class Type>
  8.     class Suma
  9.     {
  10.         public:
  11.             /** Suma los elementos de un vector
  12.              */
  13.             void sumar(Type *p, int nElementos);
  14.             Type getResult() { return _res; }
  15.         private:
  16.             Type _res;
  17.     };
  18. }
  19.  
  20. template<class Type>
  21.  void Suma<Type>::sumar(Type *p, int nElementos)
  22.  {
  23.      int i;
  24.      for(i=0;i<nElementos;i++){
  25.          _res=res+*(p+i);
  26.      }
  27.  }
  28.    
  29. #endif
  30.  


gracias de antemano.

5
C/C++ / evaluar expresion postfija
« en: Domingo 30 de Mayo de 2010, 16:14 »
hola, necesito hacer un programa en C al que le introduzcas una expresion postfija y te devuelva el resultado la expresion se guarda en una cadena con expacios entre cada dato introducido con un caracter final de parada "f", y no me funciona el programa, a ver si alguien sabe en que fallo.
Código: C
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. struct pila{
  6.     int n;
  7.     struct pila *sig;
  8. };
  9.  
  10. void apilar(struct pila **cabeza, int n);
  11. struct pila *nuevoElemento();
  12. int desapilar(struct pila **cabeza);
  13. int pilaVacia(struct pila *cabeza);
  14. int operacion(int n1, int n2, char caract);
  15. void conversion(struct pila *cabeza, char cad[]);
  16. void mostrarPila(struct pila **cabeza);
  17.  
  18. int
  19. main(void)
  20. {
  21.     int res;
  22.     struct pila *operandos=NULL;
  23.     char expresion[15];
  24.     printf("nIntroduce la expresion separada por espacios: ");
  25.     gets(expresion);
  26.     printf("nOk...getsn");
  27.     conversion(operandos, expresion);
  28.     mostrarPila(&operandos);
  29.     printf("nOk..conversionn");
  30.     res=desapilar(&operandos);
  31.     printf("nOk...resultadon");
  32.     printf("nEl resultado de la expresion es: %dn", res);
  33.     return 0;
  34. }
  35.  
  36.  
  37.  
  38. struct pila *nuevoElemento()
  39. {
  40.     return (struct pila *)malloc(sizeof(struct pila));
  41. }
  42.  
  43. void apilar(struct pila **cabeza, int n)
  44. {
  45.     struct pila *nuevo=NULL;
  46.     nuevo=nuevoElemento();
  47.     nuevo->n=n;
  48.     nuevo->sig=*cabeza;
  49.     *cabeza=nuevo;
  50. }
  51.  
  52. int desapilar(struct pila **cabeza)
  53. {
  54.     int n;
  55.     struct pila *aux=NULL;
  56.     n=(*cabeza)->n;
  57.     aux=*cabeza;
  58.     *cabeza=aux->sig;
  59.     free(aux);
  60.     return n;
  61. }
  62.  
  63. int pilaVacia(struct pila *cabeza)
  64. {
  65.     if(cabeza==NULL)
  66.         return 0;
  67.     return 1;
  68. }
  69.  
  70. int operacion(int n1, int n2, char caract)
  71. {
  72.     int r;
  73.     if(caract=='*')
  74.         r= n1*n2;
  75.     if(caract=='-')
  76.         r= n1-n2;
  77.     if(caract=='+')
  78.         r= n1+n2;
  79.     if(caract=='/')
  80.         r= n1/n2;
  81.     return r;
  82. }
  83.  
  84. void conversion(struct pila *cabeza, char cad[])
  85. {
  86.     int n1, n2, nuevo, i=0;
  87.     while(cad[i]!='f'){
  88.         if(cad[i]>47 && cad[i]<57)
  89.             apilar(&cabeza, cad[i]);
  90.         if(cad[i]>41 && cad[i]<47){
  91.             n1=desapilar(&cabeza);
  92.             n2=desapilar(&cabeza);
  93.             nuevo=operacion(n1, n2, cad[i]);
  94.             apilar(&cabeza, nuevo);
  95.         }
  96.         i++;
  97.     }
  98.    
  99. }
  100.  
  101.  
  102. void mostrarPila(struct pila **cabeza)
  103. {
  104.     struct pila *aux=NULL;
  105.     aux=*cabeza;
  106.     while(aux!=NULL){
  107.         printf("n%d",aux->n);
  108.     }
  109. }
  110.  


un saludo.

gracias de antemano.

6
C/C++ / sustituir linea de un fichero de texto
« en: Miércoles 17 de Marzo de 2010, 16:08 »
hola, estoy haciendo un programa que trabaja con un fichero de texto y necesito una función que modifique una linea, el programa consiste en introducir en un fichero de texto titulo (de un libro), autor y editorial...cada dato en una linea...tal que así:

libro1
autor1
editorial1
libro2
autor2
editorial2...

a la funcion se le pasas el titulo del libro (ya que la busqueda se hace por titulo) y también la nueva editorial, tengo esto..pero no funciona y por mas vueltas que le doy no lo saco.
Código: C
  1. void modificarEditorial(char *fichero, char *titulo, char *Nedit)
  2. {
  3.     FILE *f;
  4.     char *aux;
  5.     if((f=fopen(fichero, "r+"))==NULL){
  6.         printf("nError al abrir ficheron");
  7.         exit(-1);
  8.     }
  9.     while(fscanf(f, "%s", aux)==1){
  10.         if(strcmp(aux, titulo)==0){
  11.             fseek(f, 2, SEEK_CUR);
  12.             fputs(Nedit, f);
  13.         }
  14.     }            
  15.     fclose(f);
  16. }
  17.  

un saludo

y gracias de antemano!

7
C/C++ / bingo en C, funcion comprobar
« en: Miércoles 3 de Marzo de 2010, 18:09 »
hola, estoy haciendo un bingo en C cuyo enunciado es:
Realizar un programa para simular una sesión de Bingo en la que hay tres jugadores. Para ello, el programa debe incluir funciones para:
a)Generar los cartones. Cada cartón será una matriz aleatoria de 5 filas y 8 columnas, con valores enteros no repetidos de 0 a 99.
b)Sacar una bola del bombo. Para ello, se debe generar un número aleatorio de 0 a 99, teniendo cuidado de no generar dos veces el mismo valor.
c)Actualizar un cartón según la bola que ha salido y comprobar si el jugador ha obtenido línea (todos los valores de una línea del cartón) o bingo (todos los valores del cartón).
Para probar las funciones implementadas, simule la generación de bolas hasta que se acaben todas las bolas del bombo.

tengo todo, o eso creo pero no se exactamente como ir comprobando en con cada bola sacada si se ha hecho linea o bingo...

mi codigo:

Código: C
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4.  
  5. void gen_cartones(int *ptr);
  6. int revisarRepetido(int *ptr, int n, int lim);
  7. void mostrar(int M[][8]);
  8. int saca_bola(int *B, int i);
  9. int menu();
  10.  
  11. int
  12. main(void)
  13. {
  14.     int op=0, i=0, aux;
  15.     int C1[5][8], C2[5][8], C3[5][8], B[99];
  16.     op=menu();
  17.     while(op!=0){
  18.         switch (op){
  19.             case 1: printf("pulsa una tecla para generar el primer carton...");
  20.                     getchar();
  21.                     getchar();
  22.                     gen_cartones(C1[0]);
  23.                     printf("pulsa una tecla para generar el segundo carton...");
  24.                     getchar();
  25.                     gen_cartones(C2[0]);
  26.                     printf("pulsa una tecla para generar el tercer carton...");
  27.                     getchar();
  28.                     gen_cartones(C3[0]);
  29.                     break;
  30.             case 2: printf("npulsa una tecla para mostrar cartones...");
  31.                     getchar();
  32.                     printf("ncarton jugador 1: n");    
  33.                     mostrar(C1);
  34.                     printf("ncarton jugador 2: n");
  35.                     mostrar(C2);
  36.                     printf("ncarton jugador 3: n");
  37.                     mostrar(C3);
  38.                     break;
  39.             case 3: if(i==100)
  40.                         printf("nno se pueden sacar mas bolasn");
  41.                     else{
  42.                     aux=saca_bola(B, i);
  43.                     B[i]=aux;
  44.                     i++;
  45.                     }
  46.                     break;
  47.             default: printf("nError...introduce una opcion validan");
  48.                     break;
  49.         }
  50.         op=menu();
  51.     }    
  52.     return 0;
  53. }
  54.  
  55. void gen_cartones(int *ptr)
  56. {
  57.     int aux, i=0;
  58.     srand(time(0));
  59.     while(i<40)
  60.     {
  61.         aux=rand()%100;
  62.         if((revisarRepetido(ptr, aux, 40))==0)
  63.         {
  64.             *(ptr+i)=aux;
  65.             i++;
  66.         }
  67.     }
  68. }
  69.  
  70. int revisarRepetido(int *ptr, int n, int lim)
  71. {
  72.     int i, ret=0;
  73.     for(i=0;i<lim;i++)
  74.     {
  75.             if(*(ptr+i)==n)
  76.                 ret=1;
  77.     }
  78.     return ret;
  79. }
  80.  
  81. void mostrar(int M[][8])
  82. {
  83.     int i, j;
  84.     for(i=0;i<5;i++)
  85.     {
  86.         for(j=0;j<5;j++)
  87.         {
  88.             printf("t%d",M[i][j]);
  89.         }
  90.         printf("n");
  91.     }
  92. }
  93.  
  94. int saca_bola(int *B, int i)
  95. {
  96.     int aux=0;
  97.     srand(time(0));
  98.     aux=rand()%100;
  99.     while(revisarRepetido(B, aux, i)!=0){
  100.         aux=rand()%100;
  101.     }
  102.     return aux;
  103. }
  104.  
  105. int menu()
  106. {
  107.     int op=0;
  108.     printf("ntMENU:");
  109.     printf("nt1. Rellenar cartones.");
  110.     printf("nt2. Mostrar cartones.");
  111.     printf("nt3. Sacar bola.");
  112.     printf("nt0. Salir.");
  113.     printf("n-Seleccion: ");
  114.     scanf("%d",&op);
  115.     return op;
  116. }
  117.  

gracias de antemano!

8
C/C++ / Matriz de aleatorios sin repetir
« en: Viernes 26 de Febrero de 2010, 11:42 »
Hola, mi problema es que debo hacer un programa que genere dos matrices, una de numeros aleatorios a secas, y otra con numeros aleatorios sin repetir, y la funcion que genera la segunda matriz no me sale por muchas vueltas que le doy...un poco de ayuda no me vendria mal.

gracias.

aqui el codigo:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

void genera_alSin(int M[][5], int n);
int revisarRepetido(int M[][5], int num);
void mostrarMatriz(int M[][5]);
void genera_al(int M[][5], int n);

int
main(void)
{
    int M[5][5], lim, N[5][5];
    printf("introduce el limite para numeros aleatorios: ");
    scanf("%d",&lim);
    genera_al(M, lim);
    mostrarMatriz(M);
    printf("nahora sin repetirn");
    genera_alSin(N, lim);
    mostrarMatriz(M);
    return 0;
}

void genera_alSin(int M[][5], int n)
{
    int j=0, aux, i;
    srand(time(NULL));
    for(i=0;i<5;i++){
        while(j<5){
            aux=1+rand()%n;
         if((revisarRepetido(M, aux))==0){
            M[j++]=aux;
            }
        }
    }
}

void genera_al(int M[][5], int n)
{
    int j, aux, i;
    srand(time(NULL));
    for(i=0;i<5;i++){
        for(j=0;j<5;j++){
            aux=rand()%(n+1);
            M[j]=aux;
        }
    }
}

int revisarRepetido(int M[][5], int num)
{
   int i, j, ret=0;
   for(i=0;i<5;i++){
      for(j=0;j<5;j++){
         if(M[j]==num)
            ret=1;
      }
   }
   return ret;
}

void mostrarMatriz(int M[][5])
{
   int i, j;
    for(i=0;i<4;i++){
        for(j=0;j<4;j++){
            printf("t%d",M[j]);
        }
        printf("n");
    }
}

Páginas: [1]