|
Mostrar Temas
|
Páginas: [1] 2
|
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. #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 #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; } #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: #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: 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. #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. 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++ / 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) 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 }
|
|
|
6
|
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. 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; } } }
|
|
|
7
|
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) #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; }
|
|
|
8
|
Programación / Programación C/C++ / Modificar nodo en una lista dinámica.
|
en: 3 Marzo 2017, 16:48 pm
|
Hola, estoy haciendo una lista dinámica con nodos, y el programa ya esta básicamente funcionando completo menos la función de editByValue (Modificar por valor), creo que la lógica que uso esta mal o quizas la función compare, la verdad no detecto que hago mal, si me pueden decir lo apreciaria, gracias. Hicé 3 intentos diferentes de la misma funcion y ninguna funciona si me pueden decir como hacer funcionar cualquiera me sirve, otra cosa entiendo que no entrará al ciclo porque first lo inicializo como NULL pero aunque quite eso no funciona, preferiria un metodo que me deje incilizar a first con NULL así evito errores. El programa compila y todo nada mas esa función no sirve. Muchas gracias. Aquí el código completo #include <iostream> using namespace std;
class Nodo{ public: string element; Nodo *next; Nodo(string element){this->element=element;next=NULL;} string getElement(){return element;} };
class List{ private: Nodo *first= NULL; Nodo *last = NULL; public: void insertFirst(string element); void insertLast(string element); void insertByPos(string element, int pos); void deleteFirst(); void deleteLast(); void deleteByPos(int pos); void destroy(); void show(); void editByPos(string value,int pos); void editByValue(string value, string newValue); bool isEmpty(Nodo *first); int listSize(); };
void List::insertFirst(string element) { Nodo *temp = new Nodo(element); temp->next=NULL; if(isEmpty(first)) { first=temp; } else{ temp->next=first; first=temp; } } void List::insertLast(string element) { Nodo *temp = new Nodo(element); temp->next=NULL;
if(isEmpty(first)){ first=last=temp; } else{ Nodo *aux; aux = first; while (aux->next != NULL) { aux = aux->next; } aux->next=temp;
cout<<"\tElement "<<element<<" was inserted at the end successfully."<<endl;}
}
int List::listSize() { int c= 0; Nodo *aux; aux=first; while(aux != NULL){ aux = aux->next; c++; } return c; } void List::insertByPos(string element, int pos) { Nodo *temp = new Nodo(element); temp->next=NULL;
if(isEmpty(first)) { first=temp; cout<<"\tYou added the first element to the list successfully."<<endl; } else if (pos==1){ insertFirst(element); } else if (pos == (listSize()+1)){ insertLast(element); } else if(pos>1 && pos< (listSize() + 1)) { Nodo *aux, *aux2; aux=first; for (int i=1;i<pos;i++) { aux2 = aux; aux = aux->next; } aux2->next=temp; temp->next = aux->next; delete(aux);
cout<<"\tThe element: "<<element<<" was inserted successfully on the position: "<<pos<<"."<<endl; } else if(pos > (listSize()+1) or pos<0){ cout<<"\tError: The position that you are trying to use is invalid."<<endl; cout<<"\tThe list only have '"<<listSize()<<"' elements. Try with one that is on range."<<endl; } } void List::deleteFirst() { if(isEmpty(first)){ cout<<"\tThe list is empty, you can not delete elements."<<endl; } else{ if(first==last) { first=last=NULL; cout<<"\tThe first element was removed successfully."<<endl; } else { Nodo *aux=first; first=first->next; delete aux; cout<<"\tThe first element was removed successfully."<<endl; } } } void List::deleteLast() {
if(isEmpty(first)){ cout<<"\tThe list is empty, you can not delete elements."<<endl;}
else{ Nodo *aux=first; while(aux!=NULL) { if(first==last) { first=last=NULL; cout<<"\tThe last element was removed successfully."<<endl; } else if(aux->next==last) { Nodo *temp = last; last=aux; last->next=NULL; delete temp; cout<<"\tThe last element was removed successfully."<<endl; } aux=aux->next; } } } void List::deleteByPos(int pos) { if(isEmpty(first)){ cout<<"\tYou can not delete anything.The list is empty."<<endl; } else if (pos==1){ deleteFirst(); } else if(pos==listSize()){ deleteLast(); } else if(pos>1 && pos< (listSize() + 1)){ Nodo *aux, *aux2; aux=first; for (int i=1;i<pos;i++) { aux2 = aux; aux = aux->next; } aux2->next=aux->next; delete(aux);
cout<<"\tThe element was removed successfully of the list."<<endl; } else if(pos > (listSize()+1) or pos<0){ cout<<"\tError: The position that you are trying to use is invalid."<<endl; cout<<"\tThe list only have '"<<listSize()<<"' elements. Try with one that is on range."<<endl; } }
void List::destroy() { Nodo *aux;
while(first != NULL) { aux=first; first = first->next; delete(aux); } cout<<"\tThe list was destroyed..."<<endl; } void List::show() { if(isEmpty(first)){ cout<<"The list is Empty."<<endl;} else{ Nodo *aux; aux = first; while(aux != NULL) { cout<<aux->element<<endl; aux= aux->next; } } } void List::editByPos(string value,int pos) { if(isEmpty(first)){ cout<<"\tYou can not modify anything.The list is empty."<<endl; } else if (pos==1){
Nodo *temp = new Nodo(value); temp->next=first->next; first=temp;
cout<<"The first element is now called '"<<value<<"'."<<endl; } else if(pos>0 && pos <= (listSize())){ Nodo *temp= new Nodo(value); temp->next=NULL;
Nodo *aux, *aux2; aux=first; for (int i=1;i<pos;i++) { aux2 = aux; aux = aux->next; } aux2->next=temp; temp->next=aux->next; delete(aux); cout<<"\tThe element was modified successfully."<<endl; } else if(pos > (listSize()) or pos<=0){ cout<<"\tError: The position that you are trying to use is invalid."<<endl; cout<<"\tThe list only have '"<<listSize()<<"' elements. Try with one that is on range."<<endl; } } void List::editByValue(string value, string newValue) { //Primer intento Nodo *aux = new Nodo(value); aux=first; bool found=false; if(first != NULL){ while(aux != NULL && found != true){string temp= aux->element; if( temp.compare(value)== 0){ aux->element= newValue; found = true; } aux=aux->next; } if(!found){ cout<<"\t There is not an element with that name."<<endl; } }else{ cout<<"\t The list is empty."<<endl; } } /* Segundo intento con una logica similar pero diferente codigo *Nodo *temp = new Nodo(newValue); if(isEmpty(first)){ cout<<"\tYou can not modify anything.The list is empty."<<endl; }
Nodo *aux,*aux2; Nodo *var = first; do{ if(var->element.compare(value) != 0) { var=var->next;
}}while(var->next != NULL);
var->element = newValue; */
/* Tercer intento, tampoco funciona Nodo *temp = new Nodo(newValue); if(isEmpty(first)){ cout<<"\tYou can not modify anything.The list is empty."<<endl; }
Nodo *aux,*aux2; Nodo *var = first; do{ if(var-> element == value) { aux2=aux; aux=aux->next; temp->next=aux->next; aux2->next=temp; delete(aux);} } */
bool List::isEmpty(Nodo *first) { return(first == NULL)? true : false; }
int main () { List a; int option; int x=0; string name; int op; int opp; while(x==0){ cout<<"What do you wanna do? 1) Add 2) Delete 3) Show 4)Edit 5)Exit"<<endl; cin>>option;
switch(option) { case 1:{ cout<<"How do you want to add? \n 1)At the beginning \n 2)At the end \n 3)In 'n' position "<<endl; cin>>op; cout<<"Give me a name to add to the queue:"<<endl; cout<<" "; cin>>name; cout<<endl; if(op==1){ a.insertFirst(name);} else if (op==2){ a.insertLast(name);} else if(op==3){ int num; cout<<"In which position do you want to insert the node?"<<endl; cin>>num; a.insertByPos(name,num);} }break; case 2:{ int op,pos; cout<<"How do you want to remove?: \n 1)At the beginning \n 2)At the end \n 3)In 'n' position \n 4)Delete all the list"<<endl; cin>>op; if(op==1){ a.deleteFirst();} else if (op==2){ a.deleteLast();} else if(op==3){ int pos=0; cout<<"In which position do you want to remove the element?"<<endl; cin>>pos; a.deleteByPos(pos);} else if(op==4){ a.destroy();}
}break; case 3:{ a.show(); }break; case 4:{ int opt; string value,newName; cout<<"Do you want to: \n 1)Edit by position \n 2)Edit by value \n "<<endl; cin>>opt; cout<<"What's the new value?"<<endl; cin>>value; if(opt==1){ int pos; cout<<"In which position do you want to edit?"<<endl; cin>>pos; a.editByPos(value,pos);} else if (opt==2){ cout<<"For which value do you want to change?"<<endl; cin>>newName; a.editByValue(value, newName);} }break; case 5: x=1; } } return 0; }
|
|
|
9
|
Programación / Programación C/C++ / dificultad media en conecta 4 c++
|
en: 28 Noviembre 2016, 07:11 am
|
Buenas noches, estoy haciendo un conecta 4 en c++ ya tengo practicamente todo solo me falta el modo dificultad media vs la pc, el modo facil lo hicé con una funcion rand pero la verdad no se como hacer el medio, alguien me puede ayudar??? En si solo necesito modificar el codigo del modo facil para hacerlo dificultad media (Que bloquee las posiciones, y cada vez que haya una posibilidad de ganar ponga la ficha ahí, pero no intenta ganar por su cuenta) Comente todo el codigo para que sea mas facil y rapido entender lo que estoy haciendo. Gracias de antemano y aqui esta el codigo del modo facil: #ifndef JUGADORFACIL_H #define JUGADORFACIL_H #include <iostream> #include <cstdlib> #include <conio.h> #include <ctime> #include <string.h>
using namespace std;
class JugadorFacil { private: char tablero[6][7]; public: JugadorFacil(); int ejecutar(); bool revisar(int a, int b); void mostrar(); int fichas(int b, char jugador); };
#endif // JUGADORFACIL_H
#include "JugadorFacil.h"
JugadorFacil::JugadorFacil() { //ctor }
int JugadorFacil::ejecutar() {
//reseteo for(int a =0;a <= 5; a++){ for(int b = 0; b<=6; b++) tablero[a][b] = ' '; } //Pongo el =' ' para dejar los espacios en blanco en el tablero
mostrar(); int ficha;//guarda la variable del jugador int ficha2 = 0;//para las funciones int fichasPuestas = 0; bool juegoTerminado = false;//se cambia a true cuando todas las fichas del tablero se ponen o gana un jugador char jugador = 15;//empezara con el jugador 1 por eso es igual a 15 y luego se ira al 2 while(!juegoTerminado){//el ciclo no se termina hasta que el juego se temrina if(ficha2 != -1){//revisa si hay error cuando se pone la ficha if(jugador == 15){//cuando el jugador uno pone se cambia automaticamente al 2 al declarar jugador = 254 cout<<"Jugador 1: Donde quieres poner tu ficha?"; jugador = 254;//cambio de ficha del jugador } else{ jugador = 15;//cambio de ficha del jugador } } while(true){ if(jugador == 15){//el turno de la maquina ficha = rand()%7+1; //pondra valores aleatorios del 1-7 break;//se rompe el ciclo entonces puede continuar a la evaluacion }
if(fichasPuestas == 42) break; cin>>ficha;//esta variable guarda lo que el usuario dice ficha--;//elimino uno porque el usuario elige entre 1 y 7 y los arreglos empiezan en 0 if(ficha <=6 && ficha>= 0) break;//aqui comprueba si el valor es valido si no lo es le dira que ponga un valor valido else cout<< "\nPor favor, ingresa un valor entre 1 y 7 :"; if (cin.fail()) //esto es si ingresa un valor que no es, lo guarda en otra variable para evitar el error y preguntar por un numero valido. { // cin.clear(); // char c; // cin>>c; //en esta variable guarda el caracter no valido }
} if(fichasPuestas == 42) break;//comprueba si esta lleno ficha2 = fichas(ficha,jugador);//evalua if(ficha2 == -1) cout<<"La columna esta llena...\nPorfavor ingresa otro numero entre 1 y 7:";//si la columna esta llena te manda el mensaje else{ juegoTerminado = revisar(ficha2,ficha);//si el lugar esta vacio entonces coloca la ficha donde va fichasPuestas ++; system("cls");//esto solo limpia la pantalla mostrar();//actualiza el tablero } } system("cls"); if(fichasPuestas == 42){//si todo el tablero esta lleno y no hubo un ganador declara empate cout<<"No hay ganador!\n"; system("pause"); return 0; } if(jugador == 15)//si la variable es igual a 15(codigo ascii) gana el jugador 2 cout<<"El jugador 2 gano!!!\n"; else cout<<"El jugador 1 gano!!!\n";//de otra manera gana el 1 system("pause");//esto pausa para que se pueda ver quien gano return 0; } void JugadorFacil::mostrar() { cout<<" 1 2 3 4 5 6 7\n"; for(int a = 0; a<= 5; a++) { for(int b =0; b <= 6; b++) cout<<char(218)<<char(196)<<char(191)<<" "; cout<<'\n'; for(int b =0; b <= 6; b++) cout<<char(179)<<tablero[a][b]<<char(179)<<" "; cout<<'\n'; for(int b =0; b <= 6; b++) cout<<char(192)<<char(196)<<char(217)<<" "; cout<<'\n'; }
} bool JugadorFacil::revisar(int a, int b) { int vertical = 1; int horizontal = 1; int diagonal1 = 1; int diagonal2 = 1; char jugador = tablero[a][b]; int i; //vertical int ii;//horizontal
//revisando verticales for(i = a +1;tablero[i][b] == jugador && i <= 5;i++,vertical++);//abajo for(i = a -1;tablero[i][b] == jugador && i >= 0;i--,vertical++);//arrina if(vertical >= 4)return true; //revisando horizontales for(ii = b -1;tablero[a][ii] == jugador && ii >= 0;ii--,horizontal++);//izquierda for(ii = b +1;tablero[a][ii] == jugador && ii <= 6;ii++,horizontal++);//derecha if(horizontal >= 4) return true; //revisando diagonal 1 for(i = a -1, ii= b -1;tablero[i][ii] == jugador && i>=0 && ii >=0; diagonal1 ++, i --, ii --);//arriba e izquierda for(i = a +1, ii = b+1;tablero[i][ii] == jugador && i<=5 && ii <=6;diagonal1 ++, i ++, ii ++);//abajo y derecha if(diagonal1 >= 4) return true; //revisando diagonal 2 for(i = a -1, ii= b +1;tablero[i][ii] == jugador && i>=0 && ii <= 6; diagonal2 ++, i --, ii ++);//arriba y derecha for(i = a +1, ii= b -1;tablero[i][ii] == jugador && i<=5 && ii >=0; diagonal2 ++, i ++, ii --);//arriba e izquierda if(diagonal2 >= 4) return true; return false; } int JugadorFacil::fichas(int b, char jugador) { if(b >=0 && b<= 6) { if(tablero[0][b] == ' '){ int i; for(i = 0;tablero[i][b] == ' ';i++) if(i == 5) {tablero[i][b] = jugador; return i;} i--; tablero[i][b] =jugador; return i;
} else{ return -1; }
} else{ return -1; }
}
Muchas gracias.
|
|
|
10
|
Programación / Programación C/C++ / ayuda con programa connecta 4, para un jugador modo facil, c++
|
en: 27 Noviembre 2016, 23:38 pm
|
Buenas tardes, tengo este codigo de un juego hecho en C++ [Conecta 4] la cuestion es que funciona para 2 jugadores, cada uno va poniendo una pieza y asi. Pero necesito hacer que funcione para 1 jugador y que la maquina sea el otro en 2 modos, facil y medio, en facil lo haré con la funcion rand (aleatoria) en medio aun no lo se, pero estoy intenta convertir el codigo de 2 jugadores a 1, ya intente muchas cosas y ninguna funciona ya que la variable donde el jugador ingresa la posicion donde quiere poner la ficha es la misma en este codigo para ambos jugadores, entonces al agregar otra variable para poner la funcion aleatoria o hacer modificaciones deja de funcionar. Quiero saber si alguien puede decirme o explicarme como lo hacer esto. MUCHAS GRACIAS. Este es el codigo en una clase: Basicamente la funcion ejecutar es el main. ___________________________________________________________ #ifndef JUGADORFACIL_H #define JUGADORFACIL_H #include <iostream> #include <cstdlib> #include <conio.h> #include <ctime> #include <string.h> using namespace std; class JugadorFacil { private: char tablero[6][7]; public: JugadorFacil(); int ejecutar(); bool revisar(int a, int b); void mostrar(); int fichas(int b, char jugador); }; #include "JugadorFacil.h" JugadorFacil::JugadorFacil() { //ctor } int JugadorFacil::ejecutar() { for(int a =0;a <= 5; a++){ for(int b = 0; b<=6; b++) tablero[a][b] = ' '; } //Pongo el =' ' para dejar los espacios en blanco en el tablero mostrar(); int ficha;//Will house user row choice int ficha2 = 0;//will hold drop value int fichasPuestas = 0;//Number of peices dropped so can end game if a draw bool juegoTerminado = false;//Will be changed to true when game is won and will exit while loop char jugador = 15;//start as player 2 will change back 2 player 1 while(!juegoTerminado){//will stop when game is won, ! means NOT makes the oppisite be checked if(ficha2 != -1){//check if there was a error in the last drop if(jugador == 15){//if player 2 lasted dropped a piece so its player 1s turn cout<<"Jugador 1: Donde quieres poner tu ficha?"; jugador = 254;//char of players piece } else{ cout<<"Jugador 2: Donde quieres poner tu ficha?"; jugador = 15;//char of player piece } } while(true){//will run untill 'break;' if(fichasPuestas == 42) break;//if draw cin>>ficha;//get user input ficha--;//take off 1 to account for arrays starting at 0 not 1 if(ficha <=6 && ficha>= 0) break;//if within valid range stop loop else cout<< "\nPor favor, ingresa un valor entre 1 y 7 :";//ask for input and loop again if (cin.fail()) //catch a non number { // cin.clear(); //Stops cin trying to put its value in to hold char c; //Try entering a non number without this, 2 see what this does cin>>c; // } //Catch a non number } if(fichasPuestas == 42) break;//if draw ficha2 = fichas(ficha,jugador);//drop the player store the row in hold2 if(ficha2 == -1) cout<<"La columna esta llena...\nPorfavor ingresa otro numero entre 1 y 7:";//if error -1 row is full else{ juegoTerminado = revisar(ficha2,ficha);//check if game is run fichasPuestas ++;//another character has been succesfully placed system("cls");//This clears the screen works with windows, not nesscery to run game mostrar();//displayed updated board } } system("cls");//this clears the screen if(fichasPuestas == 42){//if draw cout<<"No hay ganador!\n"; system("pause"); return 0; } if(jugador == 15)//if won by player 2 cout<<"El jugador 2 gano!!!\n"; else cout<<"El jugador 1 gano!!!\n";//Else won by player 1 system("pause");//pauses before exit so players can see who won, works with windows return 0;//Exit application } void JugadorFacil::mostrar() // Draw board { cout<<" 1 2 3 4 5 6 7\n"; for(int a = 0; a<= 5; a++) { for(int b =0; b <= 6; b++) cout<<char(218)<<char(196)<<char(191)<<" "; cout<<'\n'; for(int b =0; b <= 6; b++) cout<<char(179)<<tablero[a][b]<<char(179)<<" "; cout<<'\n'; for(int b =0; b <= 6; b++) cout<<char(192)<<char(196)<<char(217)<<" "; cout<<'\n'; } } bool JugadorFacil::revisar(int a, int b) { int vertical = 1; int horizontal = 1; int diagonal1 = 1; int diagonal2 = 1; char jugador = tablero[a][b]; int i; //vertical int ii;//horizontal //revisando verticales for(i = a +1;tablero[i][b] == jugador && i <= 5;i++,vertical++);//Check down for(i = a -1;tablero[i][b] == jugador && i >= 0;i--,vertical++);//Check up if(vertical >= 4)return true; //revisando horizontales for(ii = b -1;tablero[a][ii] == jugador && ii >= 0;ii--,horizontal++);//Check left for(ii = b +1;tablero[a][ii] == jugador && ii <= 6;ii++,horizontal++);//Check right if(horizontal >= 4) return true; //revisando diagonal 1 for(i = a -1, ii= b -1;tablero[i][ii] == jugador && i>=0 && ii >=0; diagonal1 ++, i --, ii --);//up and left for(i = a +1, ii = b+1;tablero[i][ii] == jugador && i<=5 && ii <=6;diagonal1 ++, i ++, ii ++);//down and right if(diagonal1 >= 4) return true; //revisando diagonal 2 for(i = a -1, ii= b +1;tablero[i][ii] == jugador && i>=0 && ii <= 6; diagonal2 ++, i --, ii ++);//up and right for(i = a +1, ii= b -1;tablero[i][ii] == jugador && i<=5 && ii >=0; diagonal2 ++, i ++, ii --);//up and left if(diagonal2 >= 4) return true; return false; } int JugadorFacil::fichas(int b, char jugador) { if(b >=0 && b<= 6) { if(tablero[0][b] == ' '){ int i; for(i = 0;tablero[i][b] == ' ';i++) if(i == 5) {tablero[i][b] = jugador; return i;} i--; tablero[i][b] =jugador; return i; } else{ return -1; } } else{ return -1; } }
GRACIAS
|
|
|
|
|
|
|