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

 

 


Tema destacado:


  Mostrar Mensajes
Páginas: 1 2 [3] 4 5
21  Programación / Programación C/C++ / Re: C: Una función que reciba un parámetro desde una struct e imprima. en: 10 Abril 2016, 02:39 am
Date  ;D Espero que sea intuitivo el código :P

Código
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <windows.h>
  4.  
  5. using namespace std;
  6.  
  7. struct USER {
  8.  
  9. char nick[25];
  10. char ip[16];
  11. char email[30];
  12. };
  13.  
  14. struct CHATROOM {
  15.  
  16. int roomid;
  17. char nombre[20];
  18. int nUsers; //Número actual de usuarios
  19. USER lista[40];
  20. };
  21.  
  22. void nuevoChat(int maxChats, int &nChats, CHATROOM Chat[]); //Agrega un nuevo chat a la lista de chats
  23. int agregarUsuario(int nChats, CHATROOM Chat[]); //Agrega un usuario nuevo a un chat específico
  24. void ImprimeUsuarios(int indexChat, int nChats, CHATROOM Chat[]); //Imprime los usuarios dentro de el chat seleccionado o todos
  25. void Flush(); //Elimina la basura ( Como si fuera "flush()" )
  26.  
  27. int main() {
  28.  
  29.    int maxChats = 10; //Numero máximo de Chats
  30.    int nChats = 0; //Numero actual de Chats
  31.    char op; //Variable auxiliar para el menu de opciones
  32.    CHATROOM Chat[maxChats]; // Arreglo de chats
  33.  
  34.    //Creando un chat nuevo por defecto
  35.    Chat[nChats].roomid = nChats + 1; //Esto no es necesario en realidad, ya que no usamos el id de chat
  36.    Chat[nChats].nUsers = 0; // Ya que es un chat nuevo no contiene Usuarios, por eso se iguala a 0
  37.    strcpy(Chat[0].nombre, "CHAT 1"); //Ponemos nombre al nuevo chat
  38.    nChats++; //Aumentamos el numero de chats
  39.  
  40.    while(true) {
  41.  
  42.        system("cls");
  43.        printf("***MENU DE CHATS***\n\n");
  44.  
  45.        printf("1.- Agregar nuevo chat.\n");
  46.        printf("2.- Agregar usuario a chat.\n");
  47.        printf("3.- Imprimir usuarios de chat.\n");
  48.        printf("4.- Imprimir usuarios de chat especifico.\n");
  49.        printf("5.- Salir.\n\n");
  50.        printf("Seleccione su opcion: ");
  51.        scanf("%c", &op);
  52.  
  53.        system("cls");
  54.        Flush();
  55.  
  56.        switch(op) {
  57.  
  58.        case '1':
  59.  
  60.            nuevoChat(maxChats, nChats, Chat);
  61.            break;
  62.  
  63.        case '2':
  64.  
  65.            agregarUsuario(nChats, Chat);
  66.            break;
  67.  
  68.        case '3':
  69.  
  70.            ImprimeUsuarios(0,nChats, Chat);
  71.            break;
  72.  
  73.        case '4':
  74.  
  75.            int indexChat;
  76.            printf("Ingresa el ID del chat al que ingresara: ");
  77.            scanf("%d", &indexChat);
  78.  
  79.            while(indexChat < 0 || indexChat -1 >= nChats){
  80.  
  81.               printf("\nNo existe ningun chat con ese id!");
  82.               printf("\n\nIngresa el ID del chat al que ingresara: ");
  83.               scanf("%d", &indexChat);
  84.            }
  85.  
  86.            Flush();
  87.            system("cls");
  88.            ImprimeUsuarios(indexChat,nChats, Chat);
  89.            break;
  90.  
  91.        case '5':
  92.  
  93.            return 0;
  94.            break;
  95.  
  96.        default:
  97.  
  98.            printf("Opcion invalida! ");
  99.            break;
  100.        }
  101.  
  102.        system("Pause");
  103.    }
  104. }
  105.  
  106. void nuevoChat(int maxChats, int &nChats, CHATROOM Chat[]) {
  107.  
  108.    if(nChats < maxChats) {
  109.  
  110.        printf("***AGREGAR NUEVO CHAT***\n\n");
  111.  
  112.        Chat[nChats].nUsers = 0;
  113.  
  114.        printf("Ingresa el nombre del nuevo Chat: ");
  115.        gets(Chat[nChats].nombre);
  116.  
  117.        Chat[nChats].roomid = ++nChats;
  118.  
  119.        printf("\nChat Agregado!\n\n");
  120.    } else {
  121.  
  122.        printf("\n\nError, maximo de chats alcanzado!\n\n");
  123.    }
  124. }
  125.  
  126. int agregarUsuario(int nChats, CHATROOM Chat[]) {
  127.  
  128.    int indexChat;
  129.    USER newUs;
  130.  
  131.    printf("***AGREGAR NUEVO USUARIO***\n\n");
  132.  
  133.    printf("Ingresa el ID del chat al que ingresara: ");
  134.    scanf("%d", &indexChat);
  135.  
  136.    while(indexChat < 0 || indexChat -1 >= nChats){
  137.  
  138.       printf("\nNo existe ningun chat con ese id!");
  139.       printf("\n\nIngresa el ID del chat al que ingresara: ");
  140.       scanf("%d", &indexChat);
  141.    }
  142.  
  143.    Flush();
  144.  
  145.     printf("\n\n** Ingreso a %s **\n", Chat[indexChat - 1].nombre);
  146.  
  147.    if(Chat[indexChat - 1].nUsers <= 40) {
  148.  
  149.        printf("\nIngresa su nick: ");
  150.        gets(newUs.nick);
  151.        printf("Ingresa su IP: ");
  152.        gets(newUs.ip);
  153.        printf("Ingresa su email: ");
  154.        gets(newUs.email);
  155.  
  156.        Chat[indexChat - 1].lista[Chat[indexChat - 1].nUsers] = newUs;
  157.        Chat[indexChat - 1].nUsers++;
  158.        printf("\nUsuario agregado!\n\n");
  159.  
  160.    } else {
  161.  
  162.        printf("\nMaximo de usuarios alcanzado!\n\n");
  163.    }
  164. }
  165.  
  166. void ImprimeUsuarios(int indexChat, int nChats, CHATROOM Chat[]) {
  167.  
  168.    if(indexChat == 0) {
  169.  
  170.        for(int i = 0; i < nChats; i++) {
  171.  
  172.            printf("** USARIOS EN %d: %s **\n\n", i+1, Chat[i].nombre);
  173.  
  174.            for(int j = 0; j < Chat[i].nUsers; j++) {
  175.  
  176.                printf("- Usuario %d -\n", j+1);
  177.                printf("Nick: %s\n", Chat[i].lista[j].nick);
  178.                printf("IP: %s\n", Chat[i].lista[j].ip);
  179.                printf("Email: %s\n\n", Chat[i].lista[j].email);
  180.            }
  181.            printf("\n");
  182.        }
  183.    } else {
  184.  
  185.        printf("** USARIOS EN %d: %s **\n", indexChat, Chat[indexChat-1].nombre);
  186.  
  187.        for(int j = 0; j < Chat[indexChat-1].nUsers; j++) {
  188.  
  189.            printf("- Usuario %d -\n", j+1);
  190.            printf("Nick: %s\n", Chat[indexChat-1].lista[j].nick);
  191.            printf("IP: %s\n", Chat[indexChat-1].lista[j].ip);
  192.            printf("Email: %s\n\n", Chat[indexChat-1].lista[j].email);
  193.        }
  194.        printf("\n");
  195.    }
  196. }
  197.  
  198. void Flush() {
  199.  
  200.    char trash[10];
  201.    gets(trash);
  202. }
  203.  
22  Programación / Programación C/C++ / Re: videoclub en: 30 Diciembre 2015, 06:16 am
Bueee esta es mi sulución... Solo sería modificar para que se ordenen por precios  ;D

Dvd.h
Código
  1. #ifndef DVD_H_INCLUDED
  2. #define DVD_H_INCLUDED
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. class DVD {
  9. public:
  10.  DVD(string _Titulo, string _Categoria, string _Tiempo, string _Fecha, string _Precio):
  11.    Titulo(_Titulo), Categoria(_Categoria), Tiempo(_Tiempo), Fecha(_Fecha), Precio(_Precio){}
  12.  DVD():
  13.    Titulo("Sin Titulo"), Categoria("General"), Tiempo("00:00:00"), Fecha("01/01/1990"), Precio("$0"){}
  14.  
  15.  string dar_Titulo() const { return Titulo;}
  16.  string dar_Categoria() const { return Categoria;}
  17.  string dar_Tiempo() const { return Tiempo;}
  18.  string dar_Fecha() const { return Fecha;}
  19.  string dar_Precio() const { return Precio;}
  20.  
  21.  void mod_Titulo(const string &_Titulo) {Titulo = _Titulo;}
  22.  void mod_Categoria(const string &_Categoria) {Categoria = _Categoria;}
  23.  void mod_Tiempo(const string &_Tiempo) {Tiempo = _Tiempo;}
  24.  void mod_Fecha(const string &_Fecha) {Fecha = _Fecha;}
  25.  void mod_Precio(const string &_Precio) {Precio =_Precio;}
  26.  
  27. private:
  28.  string Titulo;
  29.  string Categoria;
  30.  string Tiempo;
  31.  string Fecha;
  32.  string Precio;
  33. };
  34.  
  35.  
  36. #endif // DVD_H_INCLUDED
  37.  

Coleccion.h
Código
  1. #ifndef COLECCION_H_INCLUDED
  2. #define COLECCION_H_INCLUDED
  3.  
  4. #include "DVD.h"
  5. #include <fstream>
  6.  
  7. using namespace std;
  8.  
  9. class Coleccion {
  10. public:
  11.  Coleccion(const string &_NArch): N_Arch(_NArch), tamano(0), capacidad(0),modificado(0) {}
  12.  ~Coleccion(){}
  13.  void cargar_datos();
  14.  void modif(const string &dato, int pos, int selec);
  15.  void anadir(const DVD _Dvd);
  16.  string buscar_Tit(const string &Titulo);
  17.  string eliminar(const string &Titulo);
  18.  string datos(int i);
  19.  string datos(int i, int sel);
  20.  int buscarn(const string &Titulo);
  21.  
  22.  void mod_Titulo(int i, const string &_Dato){ Dvd[i].mod_Titulo(_Dato);}
  23.  void mod_Categoria(int i, const string &_Dato) { Dvd[i].mod_Categoria(_Dato);}
  24.  void mod_Tiempo(int i, const string &_Dato) { Dvd[i].mod_Tiempo(_Dato);}
  25.  void mod_Fecha(int i, const string &_Dato) { Dvd[i].mod_Fecha(_Dato);}
  26.  void mod_Precio(int i, const string &_Dato) { Dvd[i].mod_Precio(_Dato);}
  27.  
  28.  void ordenar();
  29.  string ordenar_cat();
  30.  string ordenar_ano();
  31.  void guardar();
  32.  friend ostream& operator<<(ostream &os, const Coleccion &Col);
  33. private:
  34.  int buscar(const string &Titulo) const;
  35.  void agregar(const DVD &_Dvd);
  36.  void eliminar(int num);
  37.  void memoria();
  38.  DVD* Dvd;
  39.  int tamano;
  40.  int capacidad;
  41.  string N_Arch;
  42.  bool modificado;
  43. };
  44.  
  45. #endif // COLECCION_H_INCLUDED
  46.  

Coleccion.cpp
Código
  1. #include "Coleccion.h"
  2. #include <fstream>
  3. #include <sstream>
  4. #include <conio.h>
  5.  
  6. using namespace std;
  7.  
  8. void Coleccion::cargar_datos() {
  9.  int i=0;
  10.  string Data[5];
  11.  ifstream in("Coleccion.txt");
  12.  if(in.fail()){
  13.    cerr << "Error al cargar archivos!";
  14.  }
  15.  while(!in.eof()){
  16.    if(getline(in,Data[i],'\n')){
  17.    }
  18.    if(Data[i][0]=='\0'){
  19.      i=0;
  20.      continue;
  21.    }
  22.    i++;
  23.    if(i>=5){
  24.      DVD _Dvd(Data[0], Data[1], Data[2], Data[3], Data[4]);
  25.      agregar(_Dvd);
  26.      i=0;
  27.    }
  28.  }
  29. }
  30.  
  31. int Coleccion::buscarn(const string &Titulo){
  32.  int n=buscar(Titulo);
  33.  return n;
  34. }
  35.  
  36. void Coleccion::modif(const string &dato, int pos, int selec) {
  37.  string Dato_ant;
  38.  switch(selec){
  39.  case 1: Dvd[pos].mod_Titulo(dato); break;
  40.  case 2: Dvd[pos].mod_Categoria(dato); break;
  41.  case 3: Dvd[pos].mod_Tiempo(dato); break;
  42.  case 4: Dvd[pos].mod_Fecha(dato); break;
  43.  case 5: Dvd[pos].mod_Precio(dato); break;
  44.  }
  45.  ordenar();
  46. }
  47.  
  48. void Coleccion::anadir(const DVD _Dvd){
  49.    agregar(_Dvd);
  50.    ordenar();
  51. }
  52.  
  53. string Coleccion::buscar_Tit(const string &Titulo) {
  54.  int num=buscar(Titulo);
  55.  if(num!=-1){
  56.    string Datos=datos(num);
  57.    return Datos;
  58.  } else {
  59.    return "";
  60.  }
  61. }
  62.  
  63. string Coleccion::datos(int i) {
  64.  string Datos;
  65.  ostringstream os;
  66.  os<<"Titulo: "<<Dvd[i].dar_Titulo()<<endl;
  67.  os<<"Categoria: "<<Dvd[i].dar_Categoria()<<endl;
  68.  os<<"Duracion: "<<Dvd[i].dar_Tiempo()<<endl;
  69.  os<<"Fecha: "<<Dvd[i].dar_Fecha()<<endl;
  70.  os<<"Precio: $"<<Dvd[i].dar_Precio()<<endl<<endl;
  71.  Datos=os.str();
  72.  return Datos;
  73. }
  74. string Coleccion::datos(int i, int sel ) {
  75.  string Datos;
  76.  ostringstream os;
  77.  os<<"Titulo: "<<Dvd[i].dar_Titulo()<<endl;
  78.  if(sel==2)
  79.    os<<"Categoria: "<<Dvd[i].dar_Categoria()<<endl;
  80.  os<<"Duracion: "<<Dvd[i].dar_Tiempo()<<endl;
  81.  os<<"Fecha: "<<Dvd[i].dar_Fecha()<<endl;
  82.  os<<"Precio: $"<<Dvd[i].dar_Precio()<<endl<<endl;
  83.  Datos=os.str();
  84.  return Datos;
  85. }
  86.  
  87. string Coleccion::eliminar(const string &Titulo) {
  88.  string Datos_ant="";
  89.  int num=buscar(Titulo);
  90.  if(num!=-1){
  91.    Datos_ant=datos(num);
  92.    eliminar(num);
  93.  }
  94.  ordenar();
  95.  return Datos_ant;
  96. }
  97.  
  98. void Coleccion::ordenar() {
  99.    for(int i=0;i<tamano-1;i++){
  100.    for (int j=i;j<tamano;j++){
  101.      if(Dvd[i].dar_Titulo()>Dvd[j].dar_Titulo()){
  102.        DVD Aux;
  103.        Aux=Dvd[i];
  104.        Dvd[i]=Dvd[j];
  105.        Dvd[j]=Aux;
  106.      }
  107.    }
  108.  }
  109.  modificado=true;
  110.  guardar();
  111. }
  112.  
  113. string Coleccion::ordenar_cat(){
  114.  ostringstream os;
  115.  string categorias[]={"Comedia","SiFi","Romantica","Otras"};
  116.  for(int i=0;i<4;i++){
  117.    os << categorias[i]<< endl;
  118.    for(int j=0;j<tamano;j++){
  119.      if(Dvd[j].dar_Categoria()==categorias[i]){
  120.        os<<datos(j,1)<<endl<<endl;
  121.      }
  122.    }
  123.  }
  124.  string cats=os.str();
  125.  return cats;
  126. }
  127.  
  128. string Coleccion::ordenar_ano(){
  129.  ostringstream os;
  130.  for(int i=0;i<tamano-1;i++){
  131.    for (int j=i;j<tamano;j++){
  132.      if(Dvd[i].dar_Fecha()>Dvd[j].dar_Fecha()){
  133.        DVD Aux;
  134.        Aux=Dvd[i];
  135.        Dvd[i]=Dvd[j];
  136.        Dvd[j]=Aux;
  137.      }
  138.    }
  139.  }
  140.  for(int i=0;i<tamano;i++){
  141.    os<<datos(i)<<endl;
  142.  }
  143.  for(int i=0;i<tamano-1;i++){
  144.    for (int j=i;j<tamano;j++){
  145.      if(Dvd[i].dar_Titulo()>Dvd[j].dar_Titulo()){
  146.        DVD Aux;
  147.        Aux=Dvd[i];
  148.        Dvd[i]=Dvd[j];
  149.        Dvd[j]=Aux;
  150.      }
  151.    }
  152.  }
  153.  string cats=os.str();
  154.  return cats;
  155. }
  156.  
  157. void Coleccion::guardar() {
  158.  if (modificado){
  159.    ofstream out(N_Arch.c_str());
  160.    for(int i=0; i<tamano; i++){
  161.      out<<Dvd[i].dar_Titulo()<<endl;
  162.      out<<Dvd[i].dar_Categoria()<<endl;
  163.      out<<Dvd[i].dar_Tiempo()<<endl;
  164.      out<<Dvd[i].dar_Fecha()<<endl;
  165.      out<<Dvd[i].dar_Precio()<<endl;
  166.    }
  167.    out.close();
  168.    modificado=false;
  169.  }
  170. }
  171.  
  172. ostream& operator<<(ostream &os, const Coleccion &Col) {
  173.  for(int i=0;i<Col.tamano;i++){
  174.    os<<"Titulo: "<<Col.Dvd[i].dar_Titulo()<<endl;
  175.    os<<"Categoria: "<<Col.Dvd[i].dar_Categoria()<<endl;
  176.    os<<"Duracion: "<<Col.Dvd[i].dar_Tiempo()<<endl;
  177.    os<<"Fecha: "<<Col.Dvd[i].dar_Fecha()<<endl;
  178.    os<<"Precio: $"<<Col.Dvd[i].dar_Precio()<<endl<<endl;
  179.  }
  180.  return os;
  181. }
  182.  
  183. int Coleccion::buscar(const string &Titulo) const {
  184.    for(int i=0; i<tamano; i++){
  185.    if (Dvd[i].dar_Titulo()==Titulo)
  186.      return i;
  187.  }
  188.  return -1;
  189. }
  190.  
  191. void Coleccion::agregar(const DVD &_Dvd) {
  192.  if(tamano==capacidad)
  193.    memoria();
  194.  Dvd[tamano]=_Dvd;
  195.  tamano++;
  196. }
  197.  
  198. void Coleccion::eliminar(int num) {
  199.  tamano-=1;
  200.  for(int i=num;i<tamano;i++){
  201.    Dvd[i]=Dvd[i+1];
  202.  }
  203. }
  204.  
  205. void Coleccion::memoria() {
  206.  if(capacidad==0){
  207.    capacidad+=1;
  208.    Dvd=new DVD[capacidad];
  209.  }
  210.  capacidad*=2;
  211.  DVD* nuevo_Dvd=new DVD[capacidad];
  212.  for(int i=0; i<tamano; i++){
  213.    nuevo_Dvd[i]=Dvd[i];
  214.  }
  215.  delete[] Dvd;
  216.  Dvd=nuevo_Dvd;
  217. }
  218.  

Main.cpp
Código
  1. #include "Coleccion.h"
  2. #include <iostream>
  3. #include <windows.h>
  4. #include <conio.h>
  5. #include <limits>
  6.  
  7. using namespace std;
  8.  
  9. void comandos(Coleccion &);
  10. int anadir_cambiar(Coleccion&);
  11. void crear_DVD(Coleccion &);
  12. int mod_DVD(Coleccion &);
  13. void buscarNom(Coleccion &);
  14. void eliminarPel(Coleccion &);
  15. void mostrarCol(Coleccion &);
  16. void ordenarf(Coleccion &);
  17. void ordenarc(Coleccion &);
  18.  
  19. int main()
  20. {
  21.  Coleccion Col("Coleccion.txt");
  22.  Col.cargar_datos();
  23.  comandos(Col);
  24. }
  25.  
  26. void comandos(Coleccion &Col){
  27.  string comandoss[]={"Cambiar o Agregar Pelicula","Buscar Pelicula","Eliminar Pelicula","Mostrar Coleccion","Ordenar por Fecha",
  28.  "Ordenar por Categoria","Salir" };
  29.  const int COMANDOS=7;
  30.  int selec=COMANDOS-1;
  31.  do{
  32.    system("cls");
  33.    for (int i=0;i<COMANDOS;i++){
  34.      cout << "Seleccion: "<< i << " "<< comandoss[i]<<endl;
  35.    }
  36.    cin>> selec;
  37.    cin.ignore(numeric_limits<int>::max(),'\n');
  38.    switch(selec){
  39.      case 0: system("cls"); anadir_cambiar(Col); break;
  40.      case 1: system("cls"); buscarNom(Col); break;
  41.      case 2: system("cls"); eliminarPel(Col); break;
  42.      case 3: system("cls"); mostrarCol(Col); break;
  43.      case 4: system("cls"); ordenarf(Col); break;
  44.      case 5: system("cls"); ordenarc(Col); break;
  45.      case 6: exit(0);
  46.    }
  47.  }while(selec<COMANDOS-1);
  48. }
  49. void buscarNom(Coleccion &Col){
  50.  string Titulo;
  51.  cout << "Ingrese el Titulo: ";
  52.  getline(cin,Titulo,'\n');
  53.  string Data= Col.buscar_Tit(Titulo);
  54.  if(Data==""){
  55.    cout << "No se encuentra la pelicula";
  56.  } else {
  57.    cout <<Data;
  58.  }
  59.  getch();
  60. }
  61. void eliminarPel(Coleccion &Col){
  62.  string Titulo;
  63.  cout << "Ingresa el Nombre:";
  64.  getline(cin, Titulo,'\n');
  65.  string Data=Col.eliminar(Titulo);
  66.  if(Data!=""){
  67.    cout << Col.buscar_Tit(Titulo);
  68.    cout << "ha sido eliminada\n";
  69.  } else {
  70.    cout << Titulo << " No se encuentra en la Coleccion!\n";
  71.  }
  72.  getch();
  73. }
  74.  
  75. void mostrarCol(Coleccion &Col){
  76.  cout << Col;
  77.  getch();
  78. }
  79.  
  80. void ordenarf(Coleccion &Col){
  81.  cout << Col.ordenar_ano();
  82.  getch();
  83. }
  84. void ordenarc(Coleccion &Col){
  85.  cout << Col.ordenar_cat();
  86.  getch();
  87. }
  88.  
  89. int anadir_cambiar(Coleccion &Col){
  90.  int select;
  91.  do{
  92.    system("cls");
  93.    cout << "Que desea hacer?\n1)Modificar\n2)Agregar\n3)Salir\n";
  94.    cin >> select;
  95.    cin.ignore(numeric_limits<int>::max(),'\n');
  96.    switch (select)
  97.    {
  98.      case 1: mod_DVD(Col); break;
  99.      case 2: crear_DVD(Col);break;
  100.      case 3: return 1; break;
  101.    }
  102.  }while (select!=3);
  103. }
  104.  
  105. void crear_DVD (Coleccion &Col) {
  106.  string Titulo,Categoria,Tiempo,Fecha,Precio;
  107.  cout << "Ingrese el Titulo: ";
  108.  getline(cin,Titulo,'\n');
  109.  cout << "Ingrese la Categoria: ";
  110.  getline(cin,Categoria,'\n');
  111.  cout << "Ingrese el Tiempo: ";
  112.  getline(cin,Tiempo,'\n');
  113.  cout << "Ingrese la Fecha: ";
  114.  getline(cin,Fecha,'\n');
  115.  cout << "Ingrese el Precio: ";
  116.  getline(cin,Precio,'\n');
  117.  DVD _Dvd(Titulo, Categoria, Tiempo, Fecha, Precio);
  118.  Col.anadir(_Dvd);
  119. }
  120.  
  121. int mod_DVD(Coleccion &Col) {
  122.  string op[]={"Modificar Titulo","Modificar Categoria","Modificar Tiempo","Modificar Fecha","Modificar Precio","Salir" };
  123.  string Dato;
  124.  int sel;
  125.  system("cls");
  126.  cout << "Ingrese el Titulo: ";
  127.  getline(cin,Dato,'\n');
  128.  int num=Col.buscarn(Dato);
  129.  
  130.  if(num!=-1){
  131.    do{
  132.      system("cls");
  133.      for(int i=0;i<6;i++){
  134.        cout << i+1 <<") " <<op[i]<< endl;
  135.      }
  136.      cin>> sel;
  137.      cin.ignore(numeric_limits<int>::max(),'\n');
  138.      switch (sel){
  139.        case 1: cout << "Ingresa el Nuevo Titulo: "; break;
  140.        case 2: cout << "Ingresa la Nueva Categoria: "; break;
  141.        case 3: cout << "Ingresa la Nueva Duración: "; break;
  142.        case 4: cout << "Ingresa la Nueva Fecha: "; break;
  143.        case 5: cout << "Ingresa el Nuevo Precio: "; break;
  144.        case 6: return 1; break;
  145.      }
  146.      getline(cin,Dato,'\n');
  147.      Col.modif(Dato,num,sel);
  148.    }while(sel!=6);
  149.    }else{
  150.      cout << "La pelicula no está en la base de datos.";
  151.      getch();
  152.    }
  153. }
  154.  
23  Programación / Java / [APORTE] Eliminar un retweet Twitter4j v4.0.4 en: 30 Diciembre 2015, 05:45 am
Buenas compañeros, hace un rato estuve buscando como poder eliminar un retweet con el paquete Twitter4j (el cual te permite obtener datos del servidor de Twitter para poder así crear tu aplicación) mi problema era que no encontraba las funciones correctas para poder eliminar un retweet hecho por ti así que después de un buen rato di con la solución, espero les sirva! ;D
Código
  1. List<Status> retweets = twitter.getRetweets(statusID);
  2. for (Status retweet : retweets)
  3.      if (retweet.getUser().getId() == twitter.getId())
  4. twitter.destroyStatus(retweet.getId());

(Es una adaptación de un código que andaba por ahí el cual era incorrecto o al menos a mi no me funcionaba en esta versión  :xD )
24  Programación / Programación C/C++ / [Consulta] Arboles binarios en: 11 Noviembre 2015, 04:44 am
Buenas a quien lo lea!

Estoy programando un árbol binario, pero al momento de compilar el programa, la función virtual no la reconoce o no se linkea, ¿a qué se debe? o que hago mal?  :-\ ojalá puedan ayudarme, gracias!

BTNode.h :
Código
  1. #define BTNODE_H_INCLUDED
  2.  
  3. #include <sstream>
  4.  
  5. using namespace std;
  6.  
  7. template<typename IT>
  8. struct BTNode {
  9.  
  10.  IT data;
  11.  BTNode<IT>* left;
  12.  BTNode<IT>* right;
  13.  
  14.  BTNode(const IT &Data, BTNode<IT>* lv = NULL, BTNode<IT>* rv = NULL) :
  15.    data(Data), left(lv), right(rv) {}
  16.  
  17.  virtual ~BTNode() {}
  18.  
  19.  virtual string toString() const {
  20.  
  21.    ostringstream os;
  22.  
  23.    os << data;
  24.    return os.str();
  25.  }
  26. };
  27.  
  28. template <typename IT>
  29. ostream &operator<<(ostream &out, const BTNode<IT> &node) {
  30.  
  31.  return out << node.toString();
  32. }
  33.  
  34. #endif // BTNODE_H_INCLUDED
  35.  
  36.  


Binary_Tree.h:
Código
  1.  
  2. #ifndef BINARY_TREE_H_INCLUDED
  3. #define BINARY_TREE_H_INCLUDED
  4.  
  5. #include <cstddef>
  6. #include <sstream>
  7. #include <stdexcept>
  8. #include <string>
  9. #include "BTNode.h"
  10.  
  11. using namespace std;
  12.  
  13. template <typename IT>
  14. class Binary_Tree {
  15.  
  16. public:
  17.  
  18.  Binary_Tree(): root(NULL) {}
  19.  Binary_Tree(const IT &Data, const Binary_Tree<IT> &lc = Binary_Tree(), const Binary_Tree<IT> &rc = Binary_Tree()):
  20.    root(new BTNode<IT>(Data, lc.root, rc.root)) {}
  21.  
  22.  virtual ~Binary_Tree() {}
  23.  
  24.  Binary_Tree<IT> getLeftSubtree() const;
  25.  Binary_Tree<IT> getRigthSubtree() const;
  26.  const IT &getData() const;
  27.  
  28.  bool isNull() const;
  29.  bool isLeaf() const;
  30.  
  31.  virtual string toString() const; //<---esta es la función!!!!
  32.  
  33.  static Binary_Tree<IT> readBinaryTree(istream& in);
  34. Binary_Tree(BTNode<IT>* newRoot): root(newRoot) {}
  35. protected:
  36.  
  37.  
  38.  BTNode<IT>* root;
  39. };
  40.  
  41. template<typename IT>
  42. ostream &operator<<(ostream &out, const Binary_Tree<IT> &tree) {
  43.  
  44.  return out << tree.toString();
  45. }
  46.  
  47. template<typename IT>
  48. istream &operator>>(istream &in, Binary_Tree<IT> &tree) {
  49.  
  50.  tree = Binary_Tree<IT>::readBinaryTree(in);
  51.  return in;
  52. }
  53.  
  54. #endif // BINARY_TREE_H_INCLUDED
  55.  
  56.  

Binary_Tree.cpp
Código
  1. #include "Binary_Tree.h"
  2.  
  3. using namespace std;
  4.  
  5. template<typename IT>
  6. Binary_Tree<IT> Binary_Tree<IT>::getLeftSubtree() const {
  7.  
  8.  if(root == NULL) {
  9.  
  10.    throw invalid_argument("getLeftSubtree on empty tree");
  11.  }
  12.  
  13.  return Binary_Tree<IT>(root->left);
  14. }
  15.  
  16. template<typename IT>
  17. Binary_Tree<IT> Binary_Tree<IT>::getRigthSubtree() const {
  18.  
  19.  if(root == NULL) {
  20.  
  21.    throw invalid_argument("getLeftSubtree on empty tree");
  22.  }
  23.  
  24.  return Binary_Tree<IT>(root->right);
  25. }
  26.  
  27. template<typename IT>
  28. bool Binary_Tree<IT>::isLeaf() const {
  29.  
  30.  if(root != NULL) {
  31.  
  32.    return root->left == NULL && root->right == NULL;
  33.  } else {
  34.  
  35.    return true;
  36.  }
  37. }
  38.  
  39. template<typename IT>
  40. string Binary_Tree<IT>::toString() const {
  41.  
  42.  ostringstream os;
  43.  
  44.  if(isNull()) {
  45.  
  46.    os << "NULL\n";
  47.  } else {
  48.  
  49.    os << *root << "\n";
  50.    os << getLeftSubtree().toString();
  51.    os << getRigthSubtree().toString();
  52.  }
  53.  
  54.  return os.str();
  55. }
  56.  
  57.  
25  Programación / Programación C/C++ / Re: Cómo convertir un string en una lista de strings en: 25 Octubre 2015, 21:43 pm
En c
Código
  1.  
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <ctype.h>
  5.  
  6. using namespace std;
  7.  
  8. int nPal(char *cadena); //Funcion que regresa el numero de palabras.
  9.  
  10. int main() {
  11.  
  12.  char cadena[] = {"Pablito clavo un clavito en la calva de un calvito"};
  13.  
  14.  int nPalabras = nPal(cadena); // Variable que almacena el numero total de palabras en la cadena.
  15.  char tokens[nPalabras][30]; //Variable que almacena cada palabra en un espacio del arreglo.
  16.  char *token = strtok(cadena, " ,.!?"); //Función que convierte una cadena a tokens.
  17.  
  18.  nPalabras = 0;
  19.  while(token != NULL) {
  20.  
  21.    strcpy(tokens[nPalabras++], token); //Se almacena cada token (palabra) en un espacio del arreglo.
  22.    token = strtok(NULL, " ,.-!?");
  23.  }
  24.  
  25.  for(int i = 0; i < nPalabras; i++){
  26.    printf("%s\n", tokens[i]);
  27.  }
  28. }
  29.  
  30. int nPal(char *cadena) {
  31.  
  32.  int n = 0;
  33.  
  34.  for(int i = 0; i < strlen(cadena); i++) {
  35.  
  36.    if(cadena[i] == ' ') {
  37.      n++;
  38.    }
  39.  }
  40.  
  41.  return n+1;
  42. }
  43.  
  44.  

En c++
Código
  1. #include <iostream>
  2. #include <stdlib.h>
  3.  
  4. using namespace std;
  5.  
  6. int nPal(string cadena) {
  7.  
  8.  int n = 0;
  9.  
  10.  for(int i = 0; i < cadena.length(); i++) {
  11.  
  12.    if(cadena[i] == ' ' || cadena[i] == '/' || cadena[i] == '.' || cadena[i] == ',') {
  13.      n++;
  14.    }
  15.  }
  16.  
  17.  return n+1;
  18. }
  19.  
  20. int main ()
  21. {
  22.  string descomponer ("Pablito clavo un clavito en la calva de un calvito");
  23.  string token[nPal(descomponer)];
  24.  int ends=0;
  25.  int inicio=0;
  26.  int i=0;
  27.  
  28.  do{
  29.  inicio=descomponer.find_first_not_of(".,/ ",ends);
  30.  ends=descomponer.find_first_of(".,/ ",inicio);
  31.  token[i]=descomponer.substr(inicio,ends-inicio);
  32.  
  33.  cout << token[i]<<endl;
  34.  i++;
  35.  }while (ends!=-1);
  36. }
  37.  
26  Programación / Programación C/C++ / Re: Contar y comparar palabras en lenguaje c en: 25 Octubre 2015, 21:21 pm
Este es el código, solo le hace falta lo de cargar el archivo a la cadena pero eso te lo dejo a ti  ;D
Código
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <ctype.h>
  4.  
  5. using namespace std;
  6.  
  7. int toLower(char *cadena); //Funcion que convierte toda la cadena a minúsculas y regresa el numero de palabras.
  8.  
  9. int main() {
  10.  
  11.  //Se crea la variable cadena tu puedes modificar el programa para que se cargue la cadena desde el archivo.
  12.  char cadena[] = {"Hola hola mundo, este programa cuenta cuantas palabras hay en esta cadena."};
  13.  char aux[strlen(cadena)]; //Variable auxiliar para mantener la cadena original.
  14.  
  15.  strcpy(aux, cadena); //Copiamos el contenido de la cadena original a la cadena auxiliar.
  16.  
  17.  int nPalabras = toLower(aux); // Variable que almacena el numero total de palabras en la cadena.
  18.  char tokens[nPalabras][30]; //Variable que almacena cada palabra en un espacio del arreglo.
  19.  char *token = strtok(aux, " ,.!?"); //Función que convierte una cadena a tokens.
  20.  
  21.  nPalabras = 0;
  22.  while(token != NULL) {
  23.  
  24.    strcpy(tokens[nPalabras++], token); //Se almacena cada token (palabra) en un espacio del arreglo.
  25.    token = strtok(NULL, " ,.-!?");
  26.  }
  27.  
  28.  int contPal[nPalabras]; //Variable que contiene el numero de repeticiones de cada palabra.
  29.  int palRep = 0; //Variable auxiliar para ingresar al indice de "contPal".
  30.  int suma = 0;
  31.  
  32.  for(int i = 0; i <nPalabras; i++) {
  33.    contPal[i] = 0;
  34.  }
  35.  
  36.  
  37.  for(int i = 0; i < nPalabras - 1; i++) { //Ciclo que compara si una palabra es igual a otra en los tokens.
  38.  
  39.    for(int j = i+1; j < nPalabras ; j++) {
  40.  
  41.      if(strcmp(tokens[i], tokens[j]) == 0 && strcmp(tokens[i], "*") != 0){
  42.  
  43.        strcpy(tokens[j],"*"); //Si una palabra es igual a otra dentro de la cadena cambia su valor a "*" para o ser tomada en cuenta la siguiente iteración.
  44.        contPal[palRep]++;
  45.      }
  46.    }
  47.  
  48.    if(strcmp(tokens[i], "*") != 0) { //Se saca la suma de las palabras repetidas.
  49.      suma +=  contPal[palRep];
  50.      palRep++;
  51.    }
  52.  }
  53.  
  54.  palRep = 0;
  55.  printf("%s\n\n", cadena);
  56.  printf("Las palabras repetidas son:\n\n");
  57.  for(int i = 0; i <nPalabras; i++) { // Muestra la palabra y su numero de repeticiones
  58.  
  59.    if(strcmp(tokens[i], "*") != 0 && contPal[palRep] != 0 ) {
  60.  
  61.      printf("%d) %s: %d Coincidencia(s).\n", palRep, tokens[i], contPal[palRep++]);
  62.    }
  63.  }
  64.  printf("\nTotal de palabras repetidas: %d\n\n", suma);
  65. }
  66.  
  67. int toLower(char *cadena) {
  68.  
  69.  int n = 0;
  70.  
  71.  for(int i = 0; i < strlen(cadena); i++) {
  72.  
  73.    cadena[i] = tolower(cadena[i]);
  74.    if(cadena[i] == ' ') {
  75.      n++;
  76.    }
  77.  }
  78.  
  79.  return n+1;
  80. }
  81.  
27  Programación / Programación C/C++ / Re: Duda con excepciones C++ en: 7 Junio 2015, 04:48 am
Código
  1. try {
  2.      cout << Cad;
  3.      cin >> x;
  4.      if(x<Min||x>Max) {
  5.        throw out_of_range("");
  6.      }
  7.     return x;
  8.     } catch (out_of_range &ex) {
  9.       cout << "Error en el intervalo, intenta de nuevo.\n";
  10.       cin.clear();
  11.       cin.ignore(numeric_limits<int>::max(),'\n');
  12.     }

¿Para qué tiras esa excepción, pudiendo hacerlo directamente dentro del if? Además de ser más rápido, es también más claro. Si no vas a tirar excepción para fuera de la función, tirar excepción como simple "break" en el código es poco necesario.

Mejor 3 if a 1 try-throw-catch.

Y aprobecho para recordar que <stdlib.h> se puede reemplazar por <cstdlib>, ya que estás con C++.

Y bueno, preferible ponerle tipo de retorno a la función main. Más que nada, para guardar un poco las formas xD


Es que en el ejercicio del libro venía que lo pusiera así  :xD también se me hizo innecesario pero supongo es para entender como funciona, muchas gracias por tu respuesta! y gracias por lo de <cstdlib>.  ;-)
28  Programación / Programación C/C++ / Duda con excepciones C++ en: 6 Junio 2015, 22:55 pm
Buenas, en un ejercicio me piden crear una función con excepciones, una debe lanzar la excepción ios::failure  si el formato ingresado no es válido, y la otra es que el numero ingresado esté fuera del intervalo dado en los parámetros de la función (out_of_range), así como lo tengo funciona, pero quería saber si está en lo correcto o hay una mejor forma de ponerlo (con las mismas excepciones) ya que quiero que cuando ingresen un caracter muestre la excepción failure pero solo toma la que le sigue. Gracias!

Código
  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <stdlib.h>
  4. #include <limits>
  5. #include <ios>
  6.  
  7. using namespace std;
  8.  
  9. int read_int(const string &Cad, const int &Min, const int &Max) {
  10.  int x;
  11.  while (true) {
  12.    try {
  13.      cout << Cad;
  14.      cin >> x;
  15.     } catch (ios::failure &ex) {
  16.       cout << "Error en la cadena de numeros, intenta de nuevo.\n";
  17.       cin.clear();
  18.       cin.ignore(numeric_limits<int>::max(),'\n');
  19.    }
  20.    try {
  21.      if(x<Min||x>Max) {
  22.        throw out_of_range("");
  23.      }
  24.      return x;
  25.    } catch (out_of_range &ex) {
  26.       cout << "Error en el intervalo, intenta de nuevo.\n";
  27.       cin.clear();
  28.       cin.ignore(numeric_limits<int>::max(),'\n');
  29.     }
  30.  }
  31.  
  32. }
  33.  
  34. main () {
  35.  cout << read_int("Ingresa un numero entre 4 y 10: ", 4, 10);
  36. }
  37.  



He modificado el código, ya me lanza correctamente las excepciones, pero aún me queda la duda si es lo correcto.

Código
  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <stdlib.h>
  4. #include <limits>
  5. #include <ios>
  6.  
  7. using namespace std;
  8.  
  9. int read_int(const string &Cad, const int &Min, const int &Max) {
  10.  cin.exceptions(ios::failbit);
  11.  int x;
  12.  while (true) {
  13.    try {
  14.      cout << Cad;
  15.      cin >> x;
  16.      if(x<Min||x>Max) {
  17.        throw out_of_range("");
  18.      }
  19.     return x;
  20.     } catch (out_of_range &ex) {
  21.       cout << "Error en el intervalo, intenta de nuevo.\n";
  22.       cin.clear();
  23.       cin.ignore(numeric_limits<int>::max(),'\n');
  24.     }catch (ios::failure &ex) {
  25.       cerr << "Error en la cadena de numeros, intenta de nuevo.\n";
  26.       cin.clear();
  27.       cin.ignore(numeric_limits<int>::max(),'\n');
  28.    }
  29.  }
  30. }
  31.  
  32. main () {
  33.  cout << read_int("Ingresa un numero entre 4 y 10: ", 4, 10);
  34. }
  35.  
29  Programación / Programación C/C++ / Re: copiar trozos de memoria en: 1 Junio 2015, 18:16 pm
Si lo estás haciendo en C++ aquí te doy un ejemplo...
Código
  1. main ()
  2. {
  3.  string descomponer ("Juan, Carter 9/16/34");
  4.  string token[5];
  5.  int ends=0;
  6.  int inicio=0;
  7.  int i=0,dia,mes,ano;
  8.  
  9.  do{
  10.  inicio=descomponer.find_first_not_of(",/ ",ends);
  11.  ends=descomponer.find_first_of(",/ ",inicio);
  12.  token[i]=descomponer.substr(inicio,ends-inicio); //Supongo esta parte es la que quieres...
  13.  
  14.  cout << token[i]<<endl;
  15.  i++;
  16.  }while (ends!=-1);
  17.  
  18.  dia=atoi(token[2].c_str());
  19.  mes=atoi(token[3].c_str());
  20.  ano=atoi(token[4].c_str());
  21.  
  22.  cout << dia <<" " << mes <<" "<< ano;
  23. }
  24.  
30  Programación / Programación C/C++ / Re: Ayuda con Directorio en c++ en: 1 Junio 2015, 16:59 pm
Me respondo a mi mismo  :rolleyes:
Tenia que inicializar esta parte aunque en el libro no lo decía xD
Código
  1. class Directorio_Tel{
  2. public:
  3.  Directorio_Tel():capacidad(0),tamano(0){}
  4.  ~Directorio_Tel(){}
  5.  

Acá tuve que modificar esto pero no se si esté bien lo que hago, el punto es que funciona  :xD
Código
  1. void Directorio_Tel::realocar() {
  2.  
  3.  if(capacidad==0){
  4.    capacidad+=1;
  5.    Directorio=new Entrada_Directorio[capacidad];
  6.  }
  7.  capacidad*=2;
  8.  
  9.  Entrada_Directorio* nuevo_Directorio=new Entrada_Directorio[capacidad];
  10.  for(int i=0; i<tamano; i++){
  11.    nuevo_Directorio[i]=Directorio[i];
  12.  }
  13.  delete[] Directorio;
  14.  Directorio=nuevo_Directorio;
  15. }
  16.  
  17.  

Saludos y gracias :-\
Páginas: 1 2 [3] 4 5
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines