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

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


  Mostrar Mensajes
Páginas: [1] 2 3
1  Programación / Programación C/C++ / Escritura incorrecta de caracteres en manejo de archivos C++ en: 13 Septiembre 2017, 23:02 pm
Hola! Tengo el problema de que al pasar una variable para su escritura en un archivo, se pasan otros caracteres en su lugar y no se por que, imprimo la variable antes de usarla y esta correcta pero ya en el archivo se añaden datos que no corresponden y no entiendo por que, ya prove casteando la variable y aun asi no se arregla, ya no se que mas puedo hacer, muchas gracias.

LA FUNCION CAPTURAR ES LA DEL PROBLEMA, justo abajo de la generacion del health number, en esa parte al escribir el archivo, gracias.

Código:
#ifndef PATIENT_H
#define PATIENT_H


class Patient
{
    public:
        void capture();
        void show();
        void deleteP();
        void searchP();
        void edit();

    private:
        char healthNumber[30];
        char name[30];
        char ailing[30];
        char treatment[30];
};

#endif // PATIENT_H

Código:
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
#include "Patient.h"
#include <cstring>
using namespace std;

int main(){
    int op;
    Patient patient;
    int z=1;
    cout<<"---------------------------------------PATIENT INFO----------------------------------------"<<endl;
    cout<<"PLEASE TYPE EVERYTHING WITH CAPITAL LETTERS, OTHERWISE YOU MAY HAVE PROBLEMS FINDING A FILE"<<endl<<endl;
    while(z!=0){
        cout<<"What do you want to do?"<<endl;
        cout<<"\t 1)Capture"<<endl;
        cout<<"\t 2)Show"<<endl;
        cout<<"\t 3)Search"<<endl;
        cout<<"\t 4)Delete"<<endl;
        cout<<"\t 5)Edit"<<endl;
        cin>>op;

            switch(op)
            {
                case 1:
                    patient.capture();
                    break;
                case 2:
                    patient.show();
                    break;
                case 3:
                    patient.searchP();
                    break;
                case 4:
                    patient.deleteP();
                    break;
                case 5:
                    patient.edit();
                    break;
                default:
                    cout<<"Your option was invalid, type a valid number."<<endl;
            }
    }
    return 0;
}

Código:
#include "Patient.h"
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;


void Patient::capture()
{
    int hN,n,a,t;
    cout<<"Name: ";
    cin.ignore();
    cin.getline(name,30);
    cout<<"Ailing: ";
    cin.getline(ailing,30);
    cout<<"Treatmeant: ";
    cin.getline(treatment,30);
    //--------------HEALTH NUMBER GENERATOR----------------
    char *ptr;
    ptr = strtok(name," ");
    string aux = ptr;
    string letter = aux.substr(0,1);
    string add = letter;
    cout<<"Health Number: ";
    while(ptr != NULL)
    {
        ptr = strtok(NULL, " ");
        if(ptr == NULL)break;
        string aux = ptr;
        letter = aux.substr(0,1);
        add = add + letter;
    }
    char *aux1 = new char[add.length() + 1];
    strcpy(aux1, add.c_str());
    delete [] aux1;
    //-----------------------------------------------------
    cout<<add<<endl;


    ofstream write;

    write.open("Patients.txt",ios::app);
        hN = strlen(aux1);
        n = strlen(name);
        a = strlen(ailing);
        t = strlen(treatment);

        write.write((char *)&hN,sizeof(hN));
        write.write((char *)&aux1,hN);
        write.write((char *)&n,sizeof(int));
        write.write((char *)&name,n);
        write.write((char *)&a,sizeof(int));
        write.write((char *)&ailing,a);
        write.write((char *)&t,sizeof(int));
        write.write((char *)&treatment,t);
        write.close();
}
void Patient::show()
{
    int hN,n,a,t;
    ifstream read;
    read.open("Patients.txt", ios::in);
    if (!read.good())
    {
        cout<<"\n\n\tFile not found."<<endl;
    }
    else
    {
        while(!read.eof()){
            read.read((char *)&hN,sizeof(int));
            read.read((char *)&healthNumber,hN);
            healthNumber[hN]='\0';
            read.read((char *)&n,sizeof(int));
            read.read((char *)&name,n);
            name[n]='\0';
            read.read((char *)&a,sizeof(int));
            read.read((char *)&ailing,a);
            ailing[a]='\0';
            read.read((char *)&t,sizeof(int));
            read.read((char *)&treatment,t);
            treatment[t]='\0';

            if(read.eof()){break;}
                cout<<endl;
                cout<<"___________________________________"<<endl;
                cout<<"Health Number: "<<healthNumber<<endl;
                cout<<"Name: "<<name<<endl;
                cout<<"Ailing: "<<ailing<<endl;
                cout<<"Treatment: "<<treatment<<endl;
                cout<<"___________________________________"<<endl;
        }read.close();
    }
}
void Patient::searchP()
{
    int hN,n,a,t;
    string id;
    ifstream read ("Patients.txt");
    bool found = false;

    cout<<"Type de health number [ID] that you want to find: ";
    cin>>id;


    if (!read.good())
    {
        cout<<"\n\n\tFile not found."<<endl;
    }
    else
    {
        while(!read.eof() && found == false){
            read.read((char *)&hN,sizeof(int));
            read.read((char *)&healthNumber,hN);
            healthNumber[hN]='\0';
            read.read((char *)&n,sizeof(int));
            read.read((char *)&name,n);
            name[n]='\0';
            read.read((char *)&a,sizeof(int));
            read.read((char *)&ailing,a);
            ailing[a]='\0';
            read.read((char *)&t,sizeof(int));
            read.read((char *)&treatment,t);
            treatment[t]='\0';

            if(healthNumber == id){
                cout<<"______________FOUND_______________"<<endl;
                cout<<"Health Number: "<<healthNumber<<endl;
                cout<<"Name: "<<name<<endl;
                cout<<"Ailing: "<<ailing<<endl;
                cout<<"Treatment: "<<treatment<<endl;
                cout<<"___________________________________"<<endl;
                found = true;
            }

            if(read.eof()){cout<<"/t Health number not found."<<endl; break;}

        }
        read.close();
    }
}
void Patient::deleteP()
{
    string word;
    cout<<"Type the idProfile that you want to find: "<<endl;
    cin>>word;

    int hN,n,a,t;
    ifstream read;
    read.open("User.txt",ios::in);
    ofstream aux;
    aux.open("temp.txt",ios::out);
    bool found = false;

    if (!read.good())
    {
        cout<<"\n\n\tFile not found."<<endl;
    }
    else
    {
        while(!read.eof()){
            found = false;

            hN = strlen(healthNumber);
            n = strlen(name);
            a = strlen(ailing);
            t = strlen(treatment);

            read.read((char *)&hN,sizeof(int));
            read.read((char *)&healthNumber,hN);
            healthNumber[hN]='\0';
            read.read((char *)&n,sizeof(int));
            read.read((char *)&name,n);
            name[n]='\0';
            read.read((char *)&a,sizeof(int));
            read.read((char *)&ailing,a);
            ailing[a]='\0';
            read.read((char *)&t,sizeof(int));
            read.read((char *)&ailing,t);
            treatment[t]='\0';

                if(word == name){
                    cout<<"______________DELETED_______________"<<endl;
                    cout<<"Health number: "<<healthNumber<<endl;
                    cout<<"Name: "<<name<<endl;
                    cout<<"Ailing: "<<ailing<<endl;
                    cout<<"Treatment: "<<treatment<<endl;
                    cout<<"___________________________________"<<endl;
                    found = true;
                }
                else if(found == false){
                    if(read.eof()){cout<<"File not found."<<endl; break;}

                    hN = strlen(healthNumber);
                    n = strlen(name);
                    a = strlen(ailing);
                    t = strlen(treatment);

                    aux.write((char *)&hN,sizeof(int));
                    aux.write((char *)&healthNumber,hN);
                    aux.write((char *)&n,sizeof(int));
                    aux.write((char *)&name,n);
                    aux.write((char *)&a,sizeof(int));
                    aux.write((char *)&ailing,a);
                    aux.write((char *)&t,sizeof(int));
                    aux.write((char *)&treatment,t);
                }


        }
        read.close();
        aux.close();
        remove("User.txt");
        rename("temp.txt","User.txt");
    }
}
void Patient::edit()
{
    string word;
    cout<<"Type the idProfile that you want to find: "<<endl;
    cin>>word;

    int hN,n,a,t;
    ifstream read;
    read.open("User.txt",ios::in);
    ofstream aux;
    aux.open("temp.txt",ios::out);
    bool found = false;

    if (!read.good())
    {
        cout<<"\n\n\tFile not found."<<endl;
    }
    else
    {
        while(!read.eof()){
            found = false;

            hN = strlen(healthNumber);
            n = strlen(name);
            a = strlen(ailing);
            t = strlen(treatment);

            read.read((char *)&hN,sizeof(int));
            read.read((char *)&healthNumber,hN);
            healthNumber[hN]='\0';
            read.read((char *)&n,sizeof(int));
            read.read((char *)&name,n);
            name[n]='\0';
            read.read((char *)&a,sizeof(int));
            read.read((char *)&ailing,a);
            ailing[a]='\0';
            read.read((char *)&t,sizeof(int));
            read.read((char *)&ailing,t);
            treatment[t]='\0';

                if(word == name){
                    cout<<"______________DELETED_______________"<<endl;
                    cout<<"Health number: "<<healthNumber<<endl;
                    cout<<"Name: "<<name<<endl;
                    cout<<"Ailing: "<<ailing<<endl;
                    cout<<"Treatment: "<<treatment<<endl;
                    cout<<"___________________________________"<<endl;
                    found = true;
                }
                else if(found == false){
                    if(read.eof()){cout<<"File not found."<<endl; break;}

                    hN = strlen(healthNumber);
                    n = strlen(name);
                    a = strlen(ailing);
                    t = strlen(treatment);

                    aux.write((char *)&hN,sizeof(int));
                    aux.write((char *)&healthNumber,hN);
                    aux.write((char *)&n,sizeof(int));
                    aux.write((char *)&name,n);
                    aux.write((char *)&a,sizeof(int));
                    aux.write((char *)&ailing,a);
                    aux.write((char *)&t,sizeof(int));
                    aux.write((char *)&treatment,t);
                }


        }
        read.close();
        aux.close();
        remove("User.txt");
        rename("temp.txt","User.txt");
    }
}
2  Programación / Programación C/C++ / Problema creando archivo auxiliar para eliminar datos en manejo de datos con c++ en: 11 Septiembre 2017, 16:32 pm
Hola, estoy haciendo un codigo que captura, muestra, elimina, modifica y busca datos en un archivo, este a su vez incluye un campo que es otro archivo, son 2 clases, una esta hecha con delimitadores y la otra con campos de dimension. El capturar, mostrar y buscar estan funcionando, y el eliminar casi, pero tengo una duda, en la funcion eliminar no se esta creando mi archivo auxiliar para respaldar los datos nuevos sin el registro que queria eliminar y no entiendo por que si para la otra clase si funciona y se crea el archivo, agradeceria mucho si alguien me puede decir que hago mal. MUCHAS GRACIAS.

Estas son mis clases y librerias:

Código:
#include <iostream>
#include <fstream>
#include <string.h>
#include <cstring>
using namespace std;

class Profile
{

public:
    string captureP();
    string showP();
    void deleteUP();
    void searchUP();
    void editP();

    char idProfile[30];
    char level[30];
    char type[30];
};

class User: public Profile
{

public:
    void capture();
    void show();
    void deleteU();
    void searchU();
    void edit();

    char idUser[30];
    char name[30];
    char mail[40];
    char tel[20];
    char ranking[30];
    char idProfile[30];
};

Esa es mi funcion eliminar:

Código:
void User::deleteU()
{
    int op = 0;
    int ii,ll,tt;
    cout<<"What do you want to do? 1)Search by IDUSER 2) Search by IDPROFILE"<<endl;
    cin>>op;

    if(op == 1)
    {
        string del;
        cout<<"Which idUser do you want to find?"<<endl;
        cin.ignore();
        getline(cin,del);
        bool found = false;

        ifstream read;
        ifstream read2;
        ofstream aux1;
        ofstream aux2;

        int i = 0;
        int es = 0;
        aux1.open("Aux.txt",ios::out);
        aux2.open("Aux2.txt",ios::out);
        read.open("User.txt", ios::in);
        read2.open("Profile.txt", ios::in);
        char line[200];
        read.getline(line,sizeof(line));
        while(!read.eof())
        {
            char *pointer;
                ii = strlen(idProfile);
                ll = strlen(level);
                tt = strlen(type);

                read2.read((char *)&ii,sizeof(int));
                read2.read((char *)&idProfile,ii);
                idProfile[ii]='\0';
                read2.read((char *)&ll,sizeof(int));
                read2.read((char *)&level,ll);
                level[ll]='\0';
                read2.read((char *)&tt,sizeof(int));
                read2.read((char *)&type,tt);
                type[tt]='\0';

            for(int i=0; i<6; i++)
            {
                if(i==0)
                {
                    pointer = strtok(line,"|");
                    strcpy(idUser,pointer);
                    if(del == idUser)
                    {
                        es=1;
                    }
                }
                else if(i==1)
                {
                    pointer = strtok(NULL,"|");
                    strcpy(name,pointer);
                }
                else if(i==2)
                {
                    pointer = strtok(NULL,"|");
                    strcpy(mail,pointer);
                }
                else if(i==3)
                {
                    pointer = strtok(NULL,"|");
                    strcpy(tel,pointer);
                }
                else if(i==4)
                {
                    pointer = strtok(NULL,"|");
                    strcpy(ranking,pointer);
                }
                else if(i==5)
                {
                    pointer = strtok(NULL,"|");
                    //strcpy(idProfile,pointer);

                }
            }
            if(es == 0)
            {
                aux2<<idUser<<'|'<<name<<'|'<<mail<<'|'<<tel<<'|'<<ranking<<'|'<<'\n';

                cout<<" si entra 2"<<endl;
                    aux1.write((char *)&ii,sizeof(int));
                    aux1.write((char *)&idProfile,ii);
                    aux1.write((char *)&ll,sizeof(int));
                    aux1.write((char *)&level,ll);
                    aux1.write((char *)&tt,sizeof(int));
                    aux1.write((char *)&type,tt);

            }
            if(es == 1)
            {
                /////////////////////////////
                while(!read2.eof() && found == false)
                {
                    cout<<"____________DELETED______________"<<endl<<endl;
                    cout<<"ID USER: "<<idUser<<endl;
                    cout<<"NAME: "<<name<<endl;
                    cout<<"MAIL: "<<mail<<endl;
                    cout<<"TEL: "<<tel<<endl;
                    cout<<"RANKING: "<<ranking<<endl;

                    cout<<"Id profile: "<<idProfile<<endl;
                    cout<<"Level: "<<level<<endl;
                    cout<<"Type: "<<type<<endl;
                    cout<<"___________________________________"<<endl;
                    es = 0;
                    //_________________________________________________
                    //________________________________________________
                    found = true;
                }

                if(read.eof())
                {
                    cout<<"File not found"<<endl;
                    break;
                }
                /////////////////////////
                cout<<"_________________________________"<<endl<<endl;
                es = 0;
                found = true;
            }

            read.getline(line,sizeof(line));
            if(read.eof() && found == false )
            {
                cout<<"There isn't a file with this ID."<<endl;
            }
        }
        read.close();
        read2.close();
        aux1.close();
        aux2.close();
        //remove("Profile.txt");
        remove("User.txt");
        //rename("Aux.txt","Profile.txt");
        rename("Aux2.txt","User.txt");
    }
    else if(op == 2)
    {
        string word;
        cout<<"Type the idProfile that you want to find: "<<endl;
        cin>>word;

        int i,l,t;
        ifstream read ("Profile.txt");
        ofstream aux2;
        aux2.open("Aux2.txt",ios::out);
        bool found = false;

        if (!read.good())
        {
            cout<<"\n\n\tFile not found."<<endl;
        }
        else
        {
            while(!read.eof() && found == false)
            {
                read.read((char *)&i,sizeof(int));
                read.read((char *)&idProfile,i);
                idProfile[i]='\0';
                read.read((char *)&l,sizeof(int));
                read.read((char *)&level,l);
                level[l]='\0';
                read.read((char *)&t,sizeof(int));
                read.read((char *)&type,t);
                type[t]='\0';

                if(idProfile != word){
                    i = strlen(idProfile);
                    l = strlen(level);
                    t = strlen(type);

                    aux2.write((char *)&i,sizeof(int));
                    aux2.write((char *)&idProfile,i);
                    aux2.write((char *)&l,sizeof(int));
                    aux2.write((char *)&level,l);
                    aux2.write((char *)&t,sizeof(int));
                    aux2.write((char *)&type,t);
                }

                if(idProfile == word)
                {
                    cout<<"______________FOUND_______________"<<endl;
                    cout<<"Id profile: "<<idProfile<<endl;
                    cout<<"Level: "<<level<<endl;
                    cout<<"Type: "<<type<<endl;
                    cout<<"___________________________________"<<endl;
                    found = true;
                }

                if(read.eof())
                {
                    cout<<"File not found"<<endl;
                    break;
                }

            }
            read.close();
        }
    }
}
3  Programación / Programación C/C++ / Deja de funcionar, agregar y mostrar archivos con delimitadores C++ en: 4 Septiembre 2017, 06:08 am
Buenas noches, tengo un programa en el que capturo y muestro con delimitadores, intento usar tokens con la función strtok para separar el registro por los mismos delimitadores pero a la hora de imprimirlos solo me imprime el primer registro del archivo y luego deja de funcionar y no tengo idea por qué, ¿alguien sabe cual es mi error?
Segun yo el problema es con la función mostrar, pues los agrega bien en el archivo.

Muchas gracias de antemano.

Código:
#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
using namespace std;

class User{

    public:
        void capture();
        void show();
        void deleteU();
        void searchU();
        void edit();

        char idUser[30];
        char name[30];
        char mail[40];
        char tel[20];
        char ranking[30];
        char idProfile[30];
};

int main(){
    int op;
    User x;
    int z=1;
    cout<<"|||||||||||||||||||||||||||||||||||||||||FILE EDITOR||||||||||||||||||||||||||||||||||||||||"<<endl<<endl;
    cout<<"PLEASE TYPE EVERYTHING WITH CAPITAL LETTERS, OTHERWISE YOU MAY HAVE PROBLEMS FINDING A FILE"<<endl;
    while(z!=0){
        cout<<"What do you want to do?"<<endl;
        cout<<"\t 1)Capture"<<endl;
        cout<<"\t 2)Show"<<endl;
        cout<<"\t 3)Delete"<<endl;
        cout<<"\t 4)Search"<<endl;
        cout<<"\t 5)Edit"<<endl;
        cin>>op;

            switch(op)
            {
                case 1:
                    x.capture();
                    break;
                case 2:
                    x.show();
                    break;
                case 3:
                    x.deleteU();
                    break;
                case 4:
                    x.searchU();
                    break;
                case 5:
                    x.edit();
                    break;
                default:
                    cout<<"Your option was invalid, type a valid number."<<endl;
            }
    }
    return 0;
}

void User::capture()
{
    cout<<"Give me the ID USER: ";
    cin.ignore();
    cin.get(idUser,30);
    cout<<"Give me the NAME: ";
    cin.ignore();
    cin.get(name,30);
    cout<<"Give me the MAIL: ";
    cin.ignore();
    cin.get(mail,40);
    cout<<"Give me the TELEPHONE NUMBER: ";
    cin.ignore();
    cin.get(tel,20);
    cout<<"Give me the RANKING: ";
    cin.ignore();
    cin.get(ranking,30);
    cout<<"Give me the ID PROFILE: ";
    cin.ignore();
    cin.get(idProfile,30);

    ofstream write("User.txt",ios::app);
    if (!write.good())
    {
        cout<<"\n\n\tFile not found."<<endl;
    }
    else
    {
        write<<idUser<<'|'<<name<<'|'<<mail<<'|'<<tel<<'|'<<ranking<<'|'<<idProfile<<'|'<<'\n';
    }
    write.close();
}
void User::show()
{
    ifstream read;
    read.open("User.txt");
    char line[200];
    read.getline(line,sizeof(line));
    while(!read.eof()){
        for(int i=0;i<6;i++){
            char *pointer;
            if(i==0){
                pointer = strtok(line,"|");
                strcpy(idUser,pointer);
            }
            else if(i==1){
                pointer = strtok(NULL,"|");
                strcpy(name,pointer);
            }
            else if(i==2){
                pointer = strtok(NULL,"|");
                strcpy(mail,pointer);
            }
            else if(i==3){
                pointer = strtok(NULL,"|");
                strcpy(tel,pointer);
            }
            else if(i==4){
                pointer = strtok(NULL,"|");
                strcpy(ranking,pointer);
            }
            else if(i==5){
                pointer = strtok(NULL,"|");
                strcpy(idProfile,pointer);
            }
        }
                    cout<<"ID USER: "<<idUser<<endl;
                    cout<<"NAME: "<<name<<endl;
                    cout<<"MAIL: "<<mail<<endl;
                    cout<<"TEL: "<<tel<<endl;
                    cout<<"RANKING: "<<ranking<<endl;
                    cout<<"ID PROFILE: "<<idProfile<<endl;
                    cout<<"_________________________________"<<endl<<endl;
    }
    read.close();
}

void User::deleteU()
{
}
void User::searchU()
{
}
void User::edit()
{/*
    ofstream aux;
    ifstream lectura;
    encontrado=false;
    int auxClave=0;
    char auxNombre[30];
    aux.open("auxiliar.txt",ios::out);
    lectura.open("alumnos.txt",ios::in);
    if(aux.is_open() && lectura.is_open()){
        cout<<"Ingresa la Clave del Alumno que deseas Modificar: ";
        cin>>auxClave;
        lectura>>clave;
        while(!lectura.eof()){
            lectura>>nombre>>semestre>>grupo>>edad;
            if(auxClave==clave){
                encontrado=true;
                cout<<"__________________________"<<endl;
                cout<<"Clave: "<<clave<<endl;
                cout<<"Nombre: "<<nombre<<endl;
                cout<<"Semestre: "<<semestre<<endl;
                cout<<"Grupo: "<<grupo<<endl;
                cout<<"Edad: "<<edad<<endl;
                cout<<"__________________________"<<endl;
                cout<<"Ingresa el Nuevo Nombre del alumno con Clave "<<clave<<": ";
                cin>>auxNombre;
                aux<<clave<<" "<<auxNombre<<" "<<semestre<<" "<<grupo<<" "<<edad<<endl;
                cout<<"Registro Modificado"<<endl;
            }else{
                aux<<clave<<" "<<nombre<<" "<<semestre<<" "<<grupo<<" "<<edad<<endl;
            }
            lectura>>clave;
        }
    }else{
        cout<<"No se pudoAbrir el Archivo o aun no ha sido Creado"<<endl;
    }
    if(encontrado==false){
        cout<<"No se encontro ningun registro con clave "<<auxClave<<endl;
    }
    aux.close();
    lectura.close();
    remove("alumnos.txt");
    rename("auxiliar.txt","alumnos.txt");*/
}
4  Programación / Programación C/C++ / Busqueda por posicion en arboles binarios c++ en: 12 Mayo 2017, 15:35 pm
Hola,
Estoy teniendo problemas haciendo una funcion recursiva en arboles binarios, estoy intentando dar una posicion y que me retorne el valor que se encuentra en esa posicion, ya pasé demasiado tiempo intentandolo arreglar y no puedo, me deja de funcionar y así. Si alguien sabe que hago mal y me puede explicar, lo agradecería muchisimo.

Gracias de antemano.

Código:
    struct node
{
    int info;
    struct node *left;
    struct node *right;
}*root;

class BST
{
    public:
        void find(int, node **, node **);
        void insert(node *tree, node *newnode);
        void del(int);
        void case_a(node *,node *);
        void case_b(node *,node *);
        void case_c(node *,node *);
        void preorder(node *);
        void inorder(node *);
        void postorder(node *);
        void display(node *, int);
        void recupera(int pos);
        int countNodes(node *);
        int busquedaPos(node *ptr,int c,int pos);
        BST()
        {
            root = NULL;
        }
};


    int BST::busquedaPos(node *ptr,int c, int pos)
{
    while(c != pos+1){
        busquedaPos(ptr->left,c+1,pos);
        busquedaPos(ptr->right,c+1,pos);
    }
    return ptr->info;
}

void BST::recupera(int pos)
{
    int y = 1;
    if(root == NULL)
    {
        cout<<"\tEmpty tree."<<endl;
    }
    else if (pos==1){
        cout<<"Your position is the root, so the value is: "<<root->info<<". "<<endl;
    }
    else if(pos>1 && pos <= (countNodes(root)))
    {
        bool found = false;
        while( y != pos && found != true){
                cout<<"ok"<<endl;
            int plz = busquedaPos(root,y,pos);
        cout<<"ok2"<<endl;
            cout<<"Your value is: "<< plz <<endl;
                found = true;
            }
    }
    else if(pos > (countNodes(root)) or pos<0){
        cout<<"\tError: The position that you are trying to use is invalid."<<endl;
        cout<<"\tThe list only have '"<<countNodes(root)<<"' elements. Try with one that is on range."<<endl;
    }
}
5  Programación / Programación C/C++ / Re: Error invalid types of int[int] for array subscript en: 25 Abril 2017, 23:20 pm
Oh no, me equivoqué de nombre eso era todo, uff que mal, muchas gracias!
6  Programación / Programación C/C++ / Error invalid types of int[int] for array subscript en: 25 Abril 2017, 22:30 pm
Hola, estoy intentando hacer que una funcion añada elementos dependiendo el numero de veces que el usario quiera, entonces hice un ciclo con un array pero me da error al tratar de pasar el parámetro del array, mi funcion (push) originalmente recive un int, no un array en si, quiza este es el problema, pero no lo se, alguien me puede decir por qué no funciona, o una alternativa, gracias.

Mi función push:

void push(struct node** head_ref, int new_data)

Código:
 int number;
    int counter = 0;
    cout<<"How many elements do you want to add?"<<endl;
    cin>>number;
    int elements[number];

    for(int i=0;i<number;i++){
        cout<<"Add your elements: "<<endl;
        cin>>elements[i];
    }
    struct node *a = NULL;

    while(number != counter){
        counter++;
        push(&a, number[counter]); // Aquí me da el error
    }
7  Programación / Programación C/C++ / Re: Método seleccion en C++, error. en: 24 Abril 2017, 18:25 pm
Una disculpa, mira las pruebas:

Tengo una función rand para añadir los datos por cantidades, le pusé para añadir 7 datos que fueron: 478,224,169,0,334,467,41. Luego los "ordené" y quedaron así: 224,169,0,334,467,41,478.

Ahora un ejemplo que si funciona, hicé lo mismo pero ahora con 5 elementos, se añadieron: 41,467,334,0,169, estos si los ordenó correctamente.
8  Programación / Programación C/C++ / Método seleccion en C++, error. en: 24 Abril 2017, 17:30 pm
Hola, hicé un código para ordenar por método de selección una lista doblemente enlanzada, segun yo funcionaba y todo bien, pero cuando lo revisé con mas de 10 elementos ya no funciona, solo con pocos. Si por favor alguien nota que hago mal, agradecería mucho que me lo dijera, muchas gracias de antemano.

Código:
void doubleList::orderSelection()
{   int min, aux;
if (first->next==NULL)
return;
    else{
    Node *p = first;
        while(p != NULL){
            min = p->element;
    Node *j = p ->next;
while(j != NULL){
            if(j->element < min){
                aux = min;
min = j->element;
                j->element = aux;
                p->element = min;
                j= p->next;
break;
}
            j=j->next;
}
aux = p->element;
min = aux;
p = p->next;
}
    }
}
9  Programación / Programación C/C++ / Lista doblemente enlazada ordenada por método de selección en: 6 Abril 2017, 05:54 am
Hola, tengo que hacer una lista doblemente enlazada por el método de selección, para prácticar haré así por los 4 métodos pero aun tengo muchas dudas de como hacerlo. En internet no encontré mucha información de como hacerlo, de lo único que medio encontré fue del método burbuja y con modificaciones lo logré hacer funcionar. Ahora estoy con el método de selección, hicé un intento pero no funciona, no me marca error, ni deja de funcionar, simplemente se queda en la consola y no hace nada. Debo decir que tenía estos métodos implementados para arreglos y estuvé intentando convertirlos para mi lista doblemente enlazada. Por lo mismo hay unas lineas de código comentadas para guiarme.

Sería de muchisima ayuda si alguien me explica lo que hago mal en el código, que puedo leer para aprender más del tema o alguna sugerencia para mejorarlo. Muchas gracias de antemano.  :)

Aquí esta mi código:
(Lo programo en inglés porque me ayuda a practicar)

Código:
#include <iostream>
#include <stdlib.h>
using namespace std;

class Node{
    public:
        int element;
        Node *next;
        Node *prev;
        Node(int element){this->element=element; next=NULL; prev=NULL;}
};

class doubleList{
   private:
    Node *first;
    Node *last;
   public:
    doubleList(){first=last=NULL;}
    void addFirst(int element);
    void remove(int p);
    void show();
    int size();
    bool isEmpty();
    void orderBubble();
    void orderSelection();
    void orderInsertion();
    void orderQuickSort();
};

void doubleList::orderBubble()
{
    Node *p = first;
    while(p != NULL){
        Node *j = p ->next;
        while(j != NULL){
            if(p->element > j->element){
                int aux = j->element;
                j->element = p->element;
                p->element = aux;
            }
            j = j->next;
        }
        p = p->next;
    }
}
void doubleList::orderSelection()
{   int min, aux;
//for(i=0;i<data;i++)
    Node *p = first;
        while(p != NULL){
            min = p->element;
    Node *j = p ->next;
//for(j=i+1;j<data;j++)
while(j !=NULL){
//if(a[j] < a[min])
            if(j->element < min){
min = j->element;
}
}
aux = p->element;
p->element = min;
min = aux;
}

show();
}
void doubleList::addFirst(int element)
{
    Node *aux = new Node(element);

    if(isEmpty()){
        first=last=aux;
        cout<<"\tFirs element '"<<aux->element<<"' was inserted successfully."<<endl;
        cout<<endl;
    }
    else{
        aux->next=first;
        first->prev=aux;
        first=aux;
        cout<<"\tElement '"<<aux->element<<"' was inserted successfully."<<endl;
        cout<<endl;
    }
}
void doubleList::remove(int p)
{
    Node *aux;

    if(p == 1)
    {
        aux = first;
        first = first->next;
        delete aux;
    }
    else if(p == size())
    {
        aux = last;
        last = last->prev;
        delete aux;
    }
    else if (p > 1 || p < size())
    {
        aux = first;
        for(int i=1;i<p;i++)
        {
            aux = aux->next;
        }
        aux->prev->next = aux->next;
        last->prev = aux->prev;
        delete aux;
    }
    else{
        cout<<"Error: invalid position"<<endl;
    }

}

void doubleList::show()
{
    if(isEmpty())
    {
        cout<<"List empty."<<endl;
    }
    else
    {
        Node *aux = first;
        while(aux != NULL)
        {
            cout<<aux->element<<" ";
            aux = aux->next;
        }
    }
    cout<<endl;
}
int doubleList::size()
{
    Node *aux;
    aux = last;
    int c = 0;
    while(aux != NULL)
    {
        aux = aux->prev;
        c++;
    }
}
bool doubleList::isEmpty()
{
    return(first == NULL && last==NULL)? true : false;
}
//__________________________________________________________________________________

int main ()
{
    doubleList a;
    int op=0;
    int x=0;
    int name;

    while(x==0){
        cout<<"What do you wanna do?\n \t 1) Add 2) Delete 3) Show 4) Order 5) Exit"<<endl;
        cin>>op;

    switch(op)
    {
        case 1:
            system("cls");
            cout<<"Type a name to add to the list: ";
            cin>>name;
            a.addFirst(name);
            break;
        case 2:
            system("cls");
            int p;
            cout<<"Type the position that you want to remove"<<endl;
            cin>>p;
            a.remove(p);
            break;
        case 3:
            system("cls");
            a.show();
            break;
        case 4:
            system("cls");
            cout<<"Which method do you want to use? "<<endl;
            cout<<"\t1)Bubble \n\t2)Selection \n\t3)Insertion \n\t4)QuickSort"<<endl;
            cin>>op;
                switch(op){
                    case 1:
                        a.orderBubble();
                        a.show();
                        break;
                    case 2:
                        a.orderSelection();
                        a.show();
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                }
            break;
        case 5:
            system("cls");
            cout<<"Program ended..."<<endl;
            x=1;
    }
}
return 0;
}
10  Programación / Programación C/C++ / Re: Modificar nodo en una lista dinámica. en: 4 Marzo 2017, 19:29 pm
Si si, estuve revisando el código en todo lo que me dijiste y ya vi que mal lo puse en el main jaja. Creo que estaba demasiado dormida cuando hice esa parte, en si pedia el mismo valor para todo. Cambié eso y ya funciona perfectamente. Muchisimas gracias de verdad! Me ayudaste demasiado!
Páginas: [1] 2 3
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines