/
Inicio :: Foros

 F.A.Q.F.A.Q.                  Conéctese para revisar sus mensajesConéctese para revisar sus mensajes   

Porfavor, Necesito ayuda ( punteros )

 
      Índice del Foro elrincondelc.com -> Principiantes C/C++
Ver tema anterior :: Ver siguiente tema  
AutorMensaje
Lycoris



Registrado: 10 Oct 2007
Mensajes: 25

MensajePublicado: 23/11/2007 1:36 pm
Título: Porfavor, Necesito ayuda ( punteros )

Código:
/*
 *      trabajo.c
 *     
 *     lycoris <[email protected]>
 *     
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *     
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *     
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

// Librerias Utilizadas

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

/* Aqui se declaran las Funciones */
int validar_rut(int r1, int r2, int r3, int r4, int r5, int r6, int r7, int r8); /* Funcion encargada de validar el RUT */
int char_int(char letra); /* Esta función cumple de convertir un char a int */
void error(void); /* Funcion encargada de enviar un mensaje de Error */



/* Funcion Validar el RUT del Programa */

char* ValidaRUT(void)
{
/* Declaraciones de Variables */
 
int r[8],d,i;
char rut[13], resp1, *guardar[13];
 
/* Ingreso de RUT */
 
      ing_rut:
      system("cls");
         printf("\n Ingrese el Rut: ");
         scanf("%s",rut);

         if(strlen(rut)>12 || strlen(rut)<11){
         error();
         goto ing_rut;
}
         if(strlen(rut)==11){
         if(rut[1]=='.' && rut[5]=='.' && rut[9]=='-'){ // Consulta por mantener el formato
 
/* Envio de char para convertir int */
 
         r[0]=0;
         r[1]=char_int(rut[0]);
         r[2]=char_int(rut[2]);
         r[3]=char_int(rut[3]);
         r[4]=char_int(rut[4]);
         r[5]=char_int(rut[6]);
         r[6]=char_int(rut[7]);
         r[7]=char_int(rut[8]);
         d=char_int(rut[10]);
 
/* Se discrepa para los digitos terminados en O - K */
 
         if(d==100){
         if(rut[10]=='k' || rut[10]=='K'){
         d=10;
      }else{
         error();
         goto ing_rut;
}
}
         if(rut[10]=='0'){
         d=11;
}
      }else{
         error();
         goto ing_rut;
}
      }else{
         if(rut[2]=='.' && rut[6]=='.' && rut[10]=='-'){  /* Consulta por mantener el formato */
 
/* Envio de char para convertir INT */
 
         r[0]=char_int(rut[0]);
         r[1]=char_int(rut[1]);
         r[2]=char_int(rut[3]);
         r[3]=char_int(rut[4]);
         r[4]=char_int(rut[5]);
         r[5]=char_int(rut[7]);
         r[6]=char_int(rut[8]);
         r[7]=char_int(rut[9]);
         d=char_int(rut[11]);
 
/* Se discrepa para los digitos terminados en O - K */
 
         if(d==100){
         if(rut[11]=='k' || rut[11]=='K'){
         d=10;
      }else{
         error();
         goto ing_rut;
}
}
         if(rut[11]=='0'){
         d=11;
}
      }else{
         error();
         goto ing_rut;
}
}
 
/* Verifica en que cada posicion de numero sea un numero y no una letra ingresada */
 
         for(i=0;i<8;i++){
         if(r[i]==999){
         error();
         goto ing_rut;
}
}
         system("cls");
         if(d==validar_rut(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7])){// Se manda a llamar la función que valida para verificar si el RUT fue o no Valido
         printf("\n\n\n\n\t\t El Rut es Correcto \n");
      }else{
         printf("\n\n\n\n\t\tI El Rut es Invalido\n");
}
         system("pause");
         goto salida;
      
 
/* Salida del Programa */
 
         salida:
         system("cls");
            printf("\n\t\tDesea retornar al Programa? (S/N)");
            scanf("%c",&resp1);
            if(resp1=='S' || resp1=='s' || resp1=='N' || resp1=='n'){
            if(resp1=='S' || resp1=='s'){
            goto ing_rut;
      }else{
         system("cls");
            printf("\n\t\tSe le agradece por Utilizar la validación de RUT\n\t\t");
         system("pause");
}
      }else{
            goto salida;
}
            strcpy(*guardar,rut);
            
      return *guardar;
}   
 
/* Funcion Digito */
 
int validar_rut(int r1, int r2, int r3, int r4, int r5, int r6, int r7, int r8){

   int digito;

/* Calculo del Codigo */
 
         digito=r1*3+r2*2+r3*7+r4*6+r5*5+r6*4+r7*3+r8*2;
         digito=digito%11;
         digito=11-digito;
         return(digito);
}
 
int char_int(char letra)

{

/* Convierte cada Char en INT en caso de que el char no sea un numero
 * devuelveun 999 para poder hacer la validación dentro de la main y
 * en caso de ser asi arroja un mensaje de error */

         if(letra=='0'){
         return(0);
}
         if(letra=='1'){
         return(1);
}
         if(letra=='2'){
         return(2);
}
         if(letra=='3'){
         return(3);
}
         if(letra=='4'){
         return(4);
}
         if(letra=='5'){
         return(5);
}
         if(letra=='6'){
         return(6);
}
         if(letra=='7'){
         return(7);
}
         if(letra=='8'){
         return(8);
}
         if(letra=='9'){
         return(9);
}
         return(999);
}
            
 
         void error(void){
         system("cls");
         printf("\n\n\n\tVerifique los Datos. Ud a ingresado MAL, vuelva a intentarlo\n\n\n\t");
         system("pause");
}
   
/* Funcion Ingresar del Programa */

void Ingresar()


    char rut[5][15], nombre[5][30], ruttemporal[15], *recibe_rut[13];
    int  i=0, k, sw;

      *recibe_rut = ValidaRUT();
      
      printf("\n %s", *recibe_rut); [color=red]/* AQUI INTENTO RECIBIR EL RUT DE LA FUNCION VALIDAR RUT ,PERO NO SE QUE PASA
      * SE CAE EL PROGRAMA!!!!!*/[/color]
      
                if(i<5){


                    sw=0;
                    for(k=0;k<=i;k++){
                        if(strcmp(ruttemporal,rut[k])==0){
                              printf("\n YA EXISTE EL RUT");
                              sw=1;                           
                        }   
                    }
                    if(sw==0){
                        strcpy(rut[i],ruttemporal);
                        printf("\nINGRESE NOMBRE:");
                        fflush(stdin);
                        scanf("%s",nombre[i]);
                 
                        i++;
                        getchar();   
                    }   
                }else{
                   printf("\n NO HAY ESPACIO");   
                }
}


void Menu(void)
{
   int op;
   
   printf("MENU DE TRABAJADORES");
   do{
      printf("\n 1.- Ingresar un Nuevo Personal");
      printf("\n 2.- Consultar por un Personal");
      printf("\n 3.- Listar Todos las Personas");
      printf("\n 4.- Eliminar Personal");
      printf("\n 5.- Salir");
      printf("\n Opcion [ ]\b\b");
      scanf("%d",&op);
      if(op < 1 || op > 5)
      {

         printf("\n Opcion Incorrecta %d", op);
      }
   }while(op < 1 || op > 5);
   
   switch(op)
   {
      case 1:
            ValidaRUT();
            Ingresar();
            break;
      case 2:
            // Consultar();
            break;
      case 3:
            // Listar();
            break;
      case 4:
            // Eliminar();
            break;
      case 5:
            // Salir();
            break;
   }
   
}

int main()
{
   Menu();
   
   return 0;
}


[b]EN LA FUNCION INGRESAR QUIERO ALMACENAR EL VALOR QUE DIGITO EN LA FUNCION VALIDAR RUT DE TIPO CHAR PARA CONTINUAR HACIENDO EL PROGRAMA !!!![/b]
Volver arriba
digies



Registrado: 18 Nov 2005
Mensajes: 377
Ubicación: Cono Sur

MensajePublicado: 23/11/2007 4:36 pm
Título:

Hola

Como el código es un poco largo; para que podamos hacer un seguimiento rápido y fácil del mismo sería mejor que primero elimines los "gotos" y hagas del código más estructurado.

Un saludo
Volver arriba
Lycoris



Registrado: 10 Oct 2007
Mensajes: 25

MensajePublicado: 23/11/2007 5:00 pm
Título: Re: Porfavor, Necesito ayuda ( punteros )

Hola, Bueno simplificando el código, lo que necesito es esto:

FUNCIÓN QUE REGRESE UNA CADENA

Código:
#include <stdio.h>
#include <string.h>

       
char* enviar()
{
               char rut[13], *enviar_rut[13];
           
                  printf("\n Ingrese RUT : ");
                  scanf("%s", rut);
                 
                  strcpy(*enviar_rut,rut);

return *enviar_rut;

}

void recibir(){

             char* almacena[13];
               
                   *almacena = enviar();
                printf("\n El rut es %s", *almacena);
}

int main(){

      enviar();
return 0;
}

      enviar();
return 0;
}


Donde esta el error ???

Porfavor, necesito la ayuda!!!!
es urgente!!
Volver arriba
digies



Registrado: 18 Nov 2005
Mensajes: 377
Ubicación: Cono Sur

MensajePublicado: 23/11/2007 6:32 pm
Título:

En el bloque principal (main) la función "enviar" debe retornar un puntero a char, por lo tanto a su valor retornado le asignamos a una variable de tipo puntero a char (definida como global).
Luego la variable "*almacena" definida como array de puntero en la función "recibir" (que generalmente suele llamarse "procedimiento" porque no devuelve ningún valor) recibe el valor de la variable "dato".
Por lo tanto el código final (puede optimizarse aun más si se quiere) con los prototipos de funciones y otras cosas más agregadas, quedaría así:

Código:

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

char *enviar(void);
void recibir(void);

char *dato;

int main(void)
{

    dato=enviar();
    recibir();
    return EXIT_SUCCESS;
}

char *enviar(void)
{
    char rut[13], *enviar_rut[13];
    printf("\n Ingrese RUT : ");
    scanf("%s", rut);
    strcpy(*enviar_rut,rut);
    return *enviar_rut;
}

void recibir(void)
{
    char *almacena[13];
    *almacena=dato;
    printf("\n El rut es %s", *almacena);
}


Un saludo
Volver arriba
rir3760



Registrado: 01 Oct 2004
Mensajes: 3837
Ubicación: Mexico

MensajePublicado: 24/11/2007 5:35 am
Título:

¿Porque incluyes (un fragmento de) la licencia GPL en tu programa (solo curiosidad)?

En cuanto al programa este tiene varias deficiencias, para empezar si la funcion "validar_rut" requiere de ocho argumentos todos de tipo int es mas facil manejar esas ocho partes del rut como un array de ocho ints y no como variables individuales.

Tambien hay que darles nombres mas distintivos a las funciones ya que se puede confundir la funcion (y sus diferencias) de las funciones "validar_rut" y "ValidaRUT".

Dentro de esa ultima funcion utilizas scanf sin limitar el numero de caracteres que esta puede leer, con esto te arriesgas a que el programa reviente si la entrada estandar contiene una palabra de mas de doce caracteres. Para limitar la lectura a un maximo de doce caracteres se debe utilizar con scanf el indicador de tipo "%12s".

Y para obtener los numeros enteros 0, 1, 2, ... en base a los caracteres '0', '1', '2', ... no es necesario utilizar una funcion si el juego de caracteres es el ASCII (lo usual) basta con realizar la resta "ch - '0'" donde "ch" es un caracter ('0', '1', '2', ...).

Tambien hay que restructurar el programa para eliminar los gotos ya que estos deben evitarse siempre que sea posible (salvo el raro caso donde incrementen la claridad y sencillez del codigo fuente).

Ya por ultimo para leer una cadena en una funcion y devolver esta (en realidad la direccion en memoria donde se almacena) una de varias las formas la publique en tu otro tema: Ayuda porfavor, con puntero char!.

Un saludo
_________________
The capacity to learn is a gift;
The ability to learn is a skill;
The willingness to learn is a choice.
--
Rebec of Ginaz
Volver arriba
Lycoris



Registrado: 10 Oct 2007
Mensajes: 25

MensajePublicado: 25/11/2007 1:02 pm
Título:

Hola rir3760 Very Happy

Uso un Entorno IDE que se llama "Geany".
y cada vez que realizo un programa en C o en cualquier otro lenguaje.
Publica la licencia GPL de forma automatica, se debe a eso simplemente.

Muchas Gracias por Ayudarme con el Codigo !!!
Siempre lo haces Wink

Saludiños
Volver arriba
      Índice del Foro elrincondelc.com -> Principiantes C/C++
Página 1 de 1Todas las horas están en GMT - 8 Horas

 
No puede crear mensajes
No puede responder temas
No puede editar sus mensajes
No puede borrar sus mensajes
No puede votar en encuestas

(c) ElRincondelC.com

Un proyecto de UrlanHeat.com