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

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


  Mostrar Mensajes
Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
11  Programación / Bases de Datos / Re: insertar en varias tablas fk y pk en: 1 Diciembre 2016, 22:09 pm
Gracias, ahora bien segun he visto el ID  de una tabla se puede usar como indice(claro sabiendo que algunos dbms ofrecen algo que funciona con indexer) entonces este idCliente quiero que se autoincremente, hasta ese punto todo bien , pero que tal que quiera poblar varias tablas que tiene una relacion de 1 a muchos siendo IDCliente la foreign key , que se autoincremente , no se si me explico bien , para ver si soy mas claro:

tengo una fila de cliente

IDCliente   | NombreCliente
1             |  pepito

si de una aplicacion esta quiere ingresar varias filas de la tabla de Datoscliente como lo podria hacer , sabiendo que cuando hagamos insert  en clientes el unico dato que insertaremos nosotros sera solo el nombreCliente? 

gracias de antemano.

12  Programación / Bases de Datos / insertar en varias tablas fk y pk en: 1 Diciembre 2016, 03:59 am
un saludo a tod@s en el foro!!

soy nuevo en esto de base de datos ,y quiero entender algo, le explico tengo varias tablas , normalizadas y como es entendible hay una relaccion donde una de las columna de la tabla es una llave foranea de otra tabla ,entonces me gustaria ver un ejemplo de como puedo hacer un insert en ambas tablas ejemplo...


 tabla cliente ( idcliente, nombre....)
tabla datoscliente ( idcliente fk, direccion,...)

 esa seria mi tabla de prueba quisiera insertar datos en ambas tablas ,como podria hacerlo??? 
13  Programación / Programación C/C++ / Re: Ayuda, con Opciones de compilacion en: 5 Noviembre 2016, 16:12 pm
si, es cierto con hacer g++ main.cpp -o app.exe  estaria bien pero cuando lo paso a otra computadora que trabaja en la misma arquitectura de computadora , me pone ese mensaje a  parte
si muevo el ejecutable a otra carpeta y reinicio la computadora me hace mencion que para ejecutrar necesitas unas dll en windows , estas dll estan dentro del folder bin en mingw,
14  Programación / Programación C/C++ / Re: Ayuda, con Opciones de compilacion en: 4 Noviembre 2016, 22:43 pm
gracias , el tercer punto es el mas extrano , por que empese a utilizar Eclipse cree un proyecto ,compila bien y se ejecuta , pero desde que paso a solo usar makefile me da error.


y mi maquina es 64 bit ,pero las librerias son de 32 bit y cuando compila en eclipse corren bien


[edit]
lo que me gustaria entender es como poner orden al compilador para poder hacer deployment en produccion?
15  Programación / Programación C/C++ / Ayuda, con Opciones de compilacion en: 4 Noviembre 2016, 21:42 pm
Buenas a todos!!

tengo como siempre un par de preguntas :

1- estoy tratando de linkear una libreria estatica (.a) desde una ruta alternativa al path que tiene el compilador por defecto y si siempre me dice que no encuentra la libreria,
estoy usando GCC segun el manual pasando el path con la opcion -LC eso esta resuelto pero no es asi.

2- estoy tratando de utilizar la libreria .a pero sin el prefijo lib, segun varias fuentes en internet pasando -l:<Nombre_de_mi_libreira>.a eso deberia estar resuelta pero no, tambien puede ser que el problema dependa del punto 1.


 quite todas las dependencias de la libreria solamente para probar la aplicacion y este seria le siguiente punto.


3-estoy tratando de hacer una prueba fuera de la maquina que tengo en desarrollo y cuando trato de correr la aplicacion ya creada , me sale un msg que dice, que la version de la aplicacion no es compatible con la version de windows que estoy utilizando, que verifique si necesito una version de 32 o 64 bit de la aplicacion y contacte al que publica la aplicacion.


agradezco por adelantado.

16  Programación / Java / [AYUDA] jdbc , conexion que se queda colgando. en: 21 Octubre 2016, 18:37 pm
un Saludo a Todos !!

tengo un incovenienten , les cuento estoy creado una clase para que me haga de manager con las bases de datos es decir que me cree la conexion , que ejecutes los query o  alguna actulizacion y luego cierre la conexion , el siguiente incoveniente es el que tengo , mi clase se conecta bien a la base de datos (estoy usando Auntenticacion )si fallo me da error y luego si trato ingresar con un usuario valido como quiera me da la misma excepcion(rechanzando la conexion ), estoy usando Derby pero supongo que es problema de programacion, la verdad estoy perdido. dejare el codigo a ver si me pueden hechar una mano o consejo

Código
  1.  
  2. public class RockPosDBManager
  3. {
  4. private boolean debugEnable;
  5. private int     engine;
  6. private int     typeOfConn;
  7.  
  8.  
  9. private String  Embeddeddriver    = "org.apache.derby.jdbc.EmbeddedDriver";
  10. private String  Clientdriver      = "org.apache.derby.jdbc.ClientDriver";
  11. private String  mySQLClientDriver = "com.mysql.jdbc.Driver";
  12.  
  13. private String  DerbyServer   = "jdbc:derby://localhost:1527/";
  14. private String  DerbyNoServer = "jdbc:derby:/";
  15. private String  MySQLServer   = "jdbc:mysql://localhost:3306/";
  16.  
  17.  
  18. private String  DBName;
  19. private String  UserName;
  20. private String  password;
  21.  
  22.  
  23. private String finalConnectionString;
  24. private String finalDriver;
  25. private boolean    Authentication;
  26.  
  27.  
  28. private boolean    create;
  29. private Connection connection;
  30. private boolean    isConnected;
  31.  
  32.  
  33. /**
  34. * @function Print
  35. * @brief  this function Print Information on terminal console if the Debug Flag is enable.
  36. * @param String - this String is the value that will be print onto the screen
  37. * */
  38. private void Print(String templ){
  39. if( debugEnable == false) return;
  40. if( templ != null )
  41. {
  42. //System.out.printf("DEBUG :  %s\n", templ );
  43. }
  44. }
  45.  
  46.  
  47. /**
  48. * @function Print
  49. * @brief  this constructor will set the current Engine, kind of connection, we have  avaliable Derby engine and Mysql .
  50. * @param  int sqlEngine =type of Engine rockPosClient = server, embedded or Client
  51. * @see  RockPosDBEngine &  RockPosTypeConn
  52. * */
  53. public RockPosDBManager(int sqlEngine , int rockposClient, boolean created ){
  54. this.engine     = sqlEngine;
  55.    this.typeOfConn = rockposClient;
  56.    this.debugEnable     = false;
  57.    this.isConnected = false;
  58.    this.create = created;
  59. }
  60.  
  61. /**
  62. * @function setDebugVerbose
  63. * @brief  this function will turn on the Debug Flag for Terminal.
  64. * @param  none
  65. * @see  
  66. * */
  67. public void setDebugVerbose(boolean e){
  68. debugEnable=e;
  69. }
  70.  
  71. /**
  72. * @function isConnectedIntoDatabase
  73. * @brief  this Function Verify if the databe is connected;
  74. * @param  none
  75. * @see  
  76. * */
  77. public boolean isConnectedIntoDatabase(){
  78. return this.isConnected;
  79. }
  80.  
  81. /**
  82. * @function SetDBNameConn
  83. * @brief  
  84. * @param  
  85. * @see  
  86. * */
  87. public void SetDBNameConn(String DBname){
  88.     try{
  89.     if(DBname == null)
  90.     throw new Exception("DB name Is null.");
  91.  
  92.     this.DBName = DBname;
  93.     Print("DB name is : "+ DBName);
  94.  
  95.  
  96.     switch(engine){
  97.  
  98.     case RockPosDBEngine.SQL_DERBY:
  99.      Print("ENGINE SQL_DERBY");
  100.     switch(typeOfConn)
  101.     {
  102.     case RockPosTypeConn.ROCKPOS_CLIENT:
  103.      Print("Type Of Connection  ROCKPOS_CLIENT");
  104.       finalConnectionString = DerbyServer   + this.DBName;
  105.       finalDriver = Clientdriver;
  106.       break;
  107.     case RockPosTypeConn.ROCKPOS_EMBEDDED:
  108.       Print("Type Of Connection  ROCKPOS_EMBEDDED");
  109.       finalConnectionString = DerbyNoServer  + this.DBName;
  110.       finalDriver = Embeddeddriver ;
  111.       break;
  112.     case RockPosTypeConn.ROCKPOS_SERVER:
  113.       Print("Type Of Connection  ROCKPOS_SERVER");
  114.       finalConnectionString = DerbyServer   + this.DBName;
  115.       finalDriver = Clientdriver;
  116.       break;
  117.     }
  118.     break;
  119.  
  120.  
  121.     case RockPosDBEngine.SQL_MYSQL:
  122.     Print("ENGINE SQL_MYSQL");
  123.  
  124.  
  125.     switch(typeOfConn)
  126.     {
  127.     case RockPosTypeConn.ROCKPOS_CLIENT:
  128.     ///   Print("Type Of Connection  ROCKPOS_CLIENT");
  129.       finalConnectionString = MySQLServer   + this.DBName;
  130.       finalDriver = mySQLClientDriver;
  131.       break;
  132.     case RockPosTypeConn.ROCKPOS_EMBEDDED:
  133.     ////  Print("Type Of Connection  ROCKPOS_EMBEDDED");
  134.       Print("MySQL does not work in Embedded Mode yet.");
  135.       finalDriver = mySQLClientDriver;
  136.       break;
  137.     case RockPosTypeConn.ROCKPOS_SERVER:
  138.     ////  Print("Type Of Connection  ROCKPOS_SERVER");
  139.       finalConnectionString = MySQLServer  + this.DBName;
  140.       finalDriver = mySQLClientDriver;
  141.       break;
  142.     }
  143.     break;
  144.     }
  145.      Print("Connection Driver is : "+ finalDriver);
  146.      Print("Connection String is  ===> "+ finalConnectionString);
  147.     if(this.UserName != null && this.password != null)
  148.     {
  149.     Print("Authentication is  On.");
  150.     Print("User name is =[ "+this.UserName+ " ] password = [ "+ this.password +"]");
  151.     Authentication = true;
  152.     }
  153.     else
  154.     {
  155.      Print("Authentication is  On.");
  156.      Print("No user name was provide.");
  157.     Authentication = false;
  158.  
  159.     }
  160.  
  161.     }catch(Exception e)
  162.     {
  163.      e.printStackTrace();
  164.     }
  165. }
  166.  
  167. /**
  168. * @function SetCredential
  169. * @brief  
  170. * @param  
  171. * @see  
  172. * */
  173. public void SetCredential(String user, String pass){
  174.   if(user != null)
  175.   this.UserName = user;
  176.   if(pass != null)
  177.     this.password = pass;
  178. }
  179.  
  180. public void RequireAuth(boolean auth){
  181. this.Authentication = auth;
  182. }
  183.  
  184.  
  185.  
  186. /**
  187. * @function Connect
  188. * @brief  
  189. * @param  
  190. * @see  
  191. * */
  192. public boolean Connect(){
  193.  
  194. this.connection = null;
  195. try{
  196. Class.forName(finalDriver);
  197. }
  198. catch(Exception e)
  199. {
  200. e.printStackTrace();
  201.  
  202. this.isConnected = false;
  203. return this.isConnected ;
  204. }
  205.  
  206. try{
  207.  
  208. String param;
  209.   if(create == false)
  210.   {
  211.  
  212.   param =  finalConnectionString +";user="+ this.UserName+";password="+ this.password;
  213.  
  214.   }
  215.   else
  216.   {
  217.   param =  finalConnectionString +";create=true;user="+this.UserName+";password="+ this.password;
  218.  
  219.   }
  220.  
  221.    System.out.printf("Param to Server : %s", param);
  222.    this.connection = DriverManager.getConnection(param);
  223.                    if(this.connection.isValid(30)){
  224.                     this.isConnected = true;
  225.                     System.out.print("\nEsta Conectado.");
  226.                    }
  227.                    else{
  228.                     this.isConnected = false;
  229.                     System.out.print("\nno Esta Conectado.");
  230.  
  231.                    }
  232.  
  233.  
  234. }
  235. catch(SQLException e)
  236. {
  237.   int code = e.getErrorCode();
  238.   e.printStackTrace();
  239.   this.isConnected = false;
  240.   return this.isConnected;
  241. }
  242.  
  243.  
  244.      return this.isConnected;
  245.  
  246. }
  247.  
  248.  
  249. public boolean Disconnect(){
  250.  
  251.   try {
  252.     this.connection.close();
  253.     } catch (SQLException e) {
  254.  
  255.      e.printStackTrace();
  256.  return isConnected;
  257.     }
  258.     this.isConnected = false;
  259. return isConnected;  
  260. }
  261.  
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.  
  269.  
  270. public boolean Execute(String sql){
  271. ///Print("Execute");
  272. boolean res = true;
  273. if(this.isConnected == false  )
  274. {
  275.   Print("theres is not Connection");
  276.   return false;
  277. }
  278.  
  279. PreparedStatement stmt   = null;
  280. try
  281. {
  282.    stmt   =  this.connection.prepareStatement(sql);
  283.    stmt.executeUpdate(sql);
  284. }catch(Exception e){
  285. e.printStackTrace();
  286. Print("Error Executing that Query");
  287. return false;
  288. }
  289. finally{
  290. ///Print("Execute Finally");
  291. try {
  292. stmt.close();
  293.  
  294. } catch (Exception e) {
  295.        Print("Error closing Statement.");
  296. }
  297. }
  298. return res;
  299. }
  300.  
  301.  
  302.  
  303.  
  304.  
  305.  
  306.  
  307.  
  308. public ResultSet Query(String sql){
  309.  
  310. if(this.isConnected == false  )
  311. {
  312.   Print("theres is not Connection");
  313.   return null;
  314. }
  315.  
  316. Statement stmt   = null;
  317. ResultSet result = null;
  318. try
  319. {
  320.  
  321.  
  322. this.connection.setAutoCommit(true);
  323.    stmt   =  this.connection.createStatement();
  324.    result = stmt.executeQuery(sql);
  325.    if(result == null)
  326.     Print("Result is null");
  327.  
  328. }catch(Exception e){
  329. Print("Error Executing that Query");
  330. }
  331. try {
  332. stmt.close();
  333. } catch (Exception e) {
  334.            Print("Error closing Statement.");
  335. }
  336. return result;
  337. }
  338.  
  339.  
  340. public void CloseConn(){
  341. try {
  342. this.connection.close();  
  343. Print("Closing Connection");
  344.  
  345. } catch (Exception e) {
  346.          Print("Error Closing Conection.");
  347. }
  348. this.isConnected= false;
  349.  
  350. }
  351.  
  352.  
  353.  
  354.  
  355.  
  356.  
  357. }
  358.  


algo que me falto ponerle es una prueba de lo que quiero hacer
Código
  1. RockPosDBManager rm = new RockPosDBManager(RockPosDBEngine.SQL_DERBY, RockPosTypeConn.ROCKPOS_CLIENT, true);
  2. rm.SetDBNameConn(RockPosConstant.DB_PATH+"d1234f");
  3. rm.SetCredential("dbmanager", "dbmanager");
  4. boolean creado = rm.Connect();
  5. if(creado == true)
  6. System.out.println("prueba 1Creado");
  7. else{
  8. System.out.println("prueba 1 no Creado");
  9.  
  10. }
  11. String sql = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\'derby.database.defaultConnectionMode\',\'noAccess\')";
  12. creado = rm.Execute(sql);
  13. if(creado == true)
  14. System.out.println(" prueba 2 Se Ejecuto");
  15. else{
  16. System.out.println(" prueba 2 no sejecuto Creado");
  17.  
  18. }
  19.  
  20. rm.Disconnect();
  21. rm.SetDBNameConn(RockPosConstant.DB_PATH+"d1234f");
  22. rm.SetCredential("usuario2", "usuario2");
  23.    creado = rm.Connect();
  24. if(creado == true)
  25. System.out.println("\n\n\n prueba 2 Creado\n");
  26. else{
  27. System.out.println("\n\n\n prueba 2 no Creado\n");
  28.  
  29. }
  30. rm.Disconnect();
  31. rm.SetCredential("dbmanager", "dbmanager");
  32.    creado = rm.Connect();
  33. if(creado == true)
  34. System.out.println(" prueba 4 prueba pasada ");
  35. else{
  36. System.out.println("prueba 4 prueba no pasada");
  37.    return;
  38. }
  39.  
  40.  
  41.  
  42.  
17  Programación / Programación C/C++ / [ayuda] punteros en linklist en: 14 Octubre 2016, 20:53 pm
Buenas a todos !!

estoy actualmete aprendiendo a implementar una lista enlazada simple y me gustaria saber como es que los punteros estan trabajando de manerar interna para poder comunicarse, si es algo sencillo en teoria pero tengo una duda que ronda en mi cabeza hace un par de minutos, estoy siguiendo un tutorial y he entendido algunas cosas como que cada nodo (usando una estructura ) tieene un puntero a otro nodo que esta en una "lista" y al final de la lista hay uno que apunta a NULL y para este aproach estoy usando c++ y plantillas , le explico un poco como tengo mi codigo:

tengo una clase llamada List esta contiene una estructura Node que contiene el dato T y el link al sugiente elemento de la estructura .... ahora en la clase tengo 2 puntero first y curr
estos contienen el dato de la cabeza (Inicio de la estructura) y curr que contiene el frente de la estructura (front )  bien en la funcion siguiente

 
Código
  1.  
  2.    void insert(T f)
  3.    {
  4.      Node<T> *temp= new Node<T>(f);
  5.       if(first == NULL)
  6.       {
  7.       first= temp;
  8.       curr = temp;
  9.       }
  10.       else
  11.       {
  12.       curr->next=temp;
  13.       curr = temp;
  14.       }
  15.    }
  16.  
el primer if esta bien  pero esta parte en else me hace perderme por ejemeplo
Código
  1.     void Print(){
  2.     if(first == NULL) return;
  3.         curr = first;
  4.     while( curr  )
  5.     {
  6.     cout << "Value is : "<< curr->date<<endl;
  7.     curr = curr->next;
  8.     }
  9.     }
  10.  

donde curr = first
toma el first pero en la funcion Insert la que se lleno fue curr por que first tiene el link de first, alguien podria explicarme eso por favor.


Código
  1. #include <iostream>
  2.  
  3. #include <string.h>
  4. using std::cout;
  5. using std::string;
  6.  
  7. template<typename T>
  8. class List
  9. {
  10. private:
  11. template<class R>
  12. struct Node{
  13. R  date;
  14. Node *next;
  15.    Node(T t){
  16.     date = t;
  17.     next = NULL;
  18.    }
  19. };
  20.  
  21. Node<T> *first;
  22. Node<T> *curr;
  23.  
  24. public:
  25.  
  26. List(){
  27. first = NULL;
  28. curr  = NULL;
  29. }
  30.    List(int d)
  31.    {
  32.     Node<T> *temp= new Node<T>(d);
  33.     first = temp;
  34.     curr  = temp;
  35.    }
  36.  
  37.    void insert(T f)
  38.    {
  39.      Node<T> *temp= new Node<T>(f);
  40.       if(first == NULL)
  41.       {
  42.       first= temp;
  43.       curr = temp;
  44.       }
  45.       else
  46.       {
  47.       curr->next=temp;
  48.       curr = temp;
  49.       }
  50.    }
  51.  
  52.     void Print(){
  53.     if(first == NULL) return;
  54.         curr = first;
  55.     while( curr  )
  56.     {
  57.     cout << "Value is : "<< curr->date<<endl;
  58.     curr = curr->next;
  59.     }
  60.     }
  61.  
  62.  
  63.     void DeleteData(int data)
  64.     {
  65.         Node<T> *delPtr = NULL;
  66.         Node<T> *temp   = first;
  67.         curr            = first;
  68.  
  69.         while(curr != NULL && curr->date != data)
  70.         {
  71.         temp = curr;
  72.         curr = curr->next;
  73.         }
  74.  
  75.         if(curr == NULL)
  76.         {
  77.         cout << "this data is not in the list;";
  78.         }
  79.         else
  80.         {
  81.         delPtr = curr;
  82.         curr = curr->next;
  83.          temp->next = curr;
  84.         if(delPtr == first)
  85.         {
  86.         first = first->next;
  87.          temp  = NULL;
  88.         }
  89.             delete delPtr;
  90.         }
  91.  
  92.     }
  93.  
  94.  
  95.  
  96.  
  97. };
  98.  
  99.  
  100.  
  101. int main()
  102. {
  103.   List<int > ls;
  104.   ls.insert(12);
  105.   ls.insert(345);
  106.   ls.insert(345);
  107.   ls.DeleteData(345);
  108.   ls.Print();
  109. }
  110.  
  111.  
18  Programación / Programación C/C++ / Mi ejemplo de array de punteros con template en: 7 Octubre 2016, 15:58 pm
buenas a todos
me gustaria compartiles algo que estoy haciendo para aprender mas sobre los punteros y los templates, antes que nada se que podria usar una lista enlazada  y podria evitarme lo de asignarle memoria dinamica con new pero quiero tenerla asi controlada con tamano fijo.
me gustaria sus opiniones.

Código
  1.  
  2.  
  3.  
  4. template<class T>
  5. class FixedArrayTemplate
  6. {
  7. private :
  8.  int max_size;
  9.  int size;
  10.  T *Allocate_array;
  11.  bool Correct;
  12. public:
  13.  FixedArrayTemplate(const unsigned int _size)
  14.      {
  15.          Correct = CreateMemoryArray(_size);
  16.      }
  17.  
  18.  bool Push(T element)
  19.  {
  20.  if(size < max_size)
  21.  {
  22.  Allocate_array[size] = element;
  23.  size++;
  24.  return true;
  25.  }
  26.  else
  27.  return false;
  28.  
  29.  }
  30.     bool isCorrect(){return Correct;}
  31.  
  32.     void Clean()
  33.     {
  34.     if(this->Correct) delete[] this->Allocate_array;
  35.     this->Allocate_array = NULL;
  36.     this->Correct = false;
  37.     size = 0;
  38.     max_size = 0;
  39.     }
  40.  
  41.      bool CreateMemoryArray(int _size)
  42.      {
  43.      if(this->isCorrect())
  44.          this->Clean();
  45.  
  46.  max_size = _size;
  47.  size     = 0;
  48.  Allocate_array = new T[_size];
  49.  if(Allocate_array == 0)
  50.  {
  51. Correct = false;
  52. return Correct;
  53.  }
  54.  else
  55.  {
  56.  Correct = true;
  57.  return Correct;
  58.  }
  59.  
  60.      }
  61.  
  62.  
  63.      T getElement(int e)
  64.      {
  65.      if(( e > 0 && e < size ) && e < this->max_size )
  66.      {
  67.     if(this->Correct)
  68.      return this->Allocate_array[e - 1];
  69.      }
  70.      else
  71.      {
  72.  
  73.     if(this->Correct)
  74.      return this->Allocate_array[size - 1];
  75.      }
  76.      }
  77.  
  78.  
  79.  
  80.     ~FixedArrayTemplate()
  81.     {
  82.            Clean();
  83.     }
  84. };
  85.  
  86.  
  87. int main()
  88. {
  89.  
  90.   char *buffer1 ="buffer 1 ";
  91.   char *buffer2 = "buffer 2";
  92.   char *buffer3 = "buffer 3";
  93.   char *buffer4 = "buffer 4";
  94.   char *buffer5 = "buffer 5";
  95.   FixedArrayTemplate<char *>miArray(20);
  96.   if(miArray.isCorrect())
  97.   {
  98.   miArray.Push(buffer1);
  99.   miArray.Push(buffer2);
  100.   miArray.Push(buffer);
  101.   miArray.Push(buffer3);
  102.   miArray.Push(buffer4);
  103.   miArray.Push(buffer5);
  104.   cout << miArray.getElement(0)<<endl;
  105.   cout << miArray.getElement(1)<<endl;
  106.   cout << miArray.getElement(2)<<endl;
  107.   cout << miArray.getElement(3)<<endl;
  108.   cout << miArray.getElement(4)<<endl;
  109.   cout << miArray.getElement(5)<<endl;
  110.   cout << miArray.getElement(6)<<endl;
  111.   }
  112.  
  113. }
  114.  
  115.  
  116.  


gracias su opinion es muy importante.
19  Programación / Programación C/C++ / Re: Cortar Cadena en: 2 Octubre 2016, 17:32 pm
hey es cierto .... waaoooo donde se fue mi logica , :D , la verdad es asi que deberia de ser. gracias.



ahora bien me encuentro en la necesidad de mutar el "string"


por ejemplo
Código
  1. /*
  2.     @function :CutStr
  3.     @param    :
  4.     @author(s) : bash &  ivancea96(staff elhacker.net)
  5.     @descripcion : Esta funcion corta una parte de la cadena pasada szChar
  6.                          mandatorio: szChars debe ser creada usando new
  7. */
  8. void CutStr(int beg, int end , char **szChars)
  9. {
  10.       int lenght = strlen(szCharsl);
  11. char* cadenaFinal = new char[lenght - end + beg + 1];
  12. memcpy(cadenaFinal, szChars, beg);
  13. memcpy(cadenaFinal+beg, szChars+end, lenght - end);
  14. cadenaFinal[lenght - end + beg] = '\0';
  15.  
  16.        ////aqui es mi duda.
  17.        delete [] *szChars;
  18.        *szChars = NULL;
  19.        *szChars = new char[lenght - end + beg + 1];
  20.        memcpy(*szChars, cadenaFinal, (lenght - end + beg));
  21.      ////
  22.       delete []cadenaFinal;
  23.       cadenaFinal = NULL;
  24. }
  25.  
  26.  


En esta parte del codigo me tira un bad_alloc y a veces solo sale pero me imagino que es por lo mismo.




Código
  1.  
  2. int main()
  3. {
  4.    char *test = new char[32];
  5.    memcpy(test, "hola que tal", 12);
  6.    CutStr(0,  4,  *test);
  7.    ///...
  8.    delete[] test;
  9. }
  10.  
  11.  




quizas mi codigo esta mal ,pero estoy haciendo esto para arm-11 en thumb mode. solo en caso de que le paresca extrano la pregunta. :D

gracias de antemano.
20  Programación / Programación C/C++ / Re: Cortar Cadena en: 1 Octubre 2016, 14:32 pm
primero que todo gracias por las respuestas !!!

@Mafus : lo que quiero hacer es lo siguiente , te muestro con un ejemplo
Código
  1.  
  2. char *cadena = "esta cadena  especial";
  3.  
  4. CutString(cadena, 5, 12);
  5.  
  6. cadena == "esta especial"
  7.  
  8.  

es decir elimine de la cadena los caracteres del 5 al 12 claro mi funcion esta dentro de una clase por eso uso this.


@ivancea96 estoy usando c++ pero lo que estoy haciendo es creando una clase "String" ademas como explique arriba quiero eliminarlo del string actual no deseo devolverlo, de hecho la funcion es de tipo int(edite mal esa parte cuand postea ) , cierto debi verificar que inlen sea diferente de "0" pero como siempre la estuve probando con una longitud mayor de 0 no me di cuenta de eso.


Código
  1. szBeg           = (char *)malloc(beg * sizeof(char ));
  2. szEnd           = (char *)malloc(( inlen - end )* sizeof(char ));
  3. szCharsCopy = (char *)malloc((beg + (inlen - end) + 1)* sizeof(char ));
  4.  
  5.  
  6. ///strncpy( szBeg, &this->szChars[0], beg);
  7. ///strncpy( szEnd, &this->szChars[end], inlen);
  8. memcpy( szBeg, &this->szChars[0], beg);
  9.        memcpy( szEnd, &this->szChars[end], inlen - end);
  10.  
  11.  
  12. strncat( szCharsCopy, szBeg , strlen(szBeg));
  13. strncat( szCharsCopy , szEnd, strlen(szEnd));
  14.        szChasrsCopy[beg + (inlen - end))+1] = '\0';
  15.  
  16.  


 dices algo asi ?
 como me recomiendas tomar espacio una sola vez ?

gracias de nuevo por todo ;-) :laugh:

EDIT:


He mejorado el codigo , me gustaria saber su opinion acerca de este.

Código
  1. char * CutString(char *Chars, int beg_, int end_)
  2. {
  3. char *beg = (char *)malloc( beg_ * sizeof(char) );
  4. char *end = (char *)malloc( (strlen(Chars) - end_) * sizeof(char) );
  5.  
  6. cout << beg_<<endl;
  7. cout << end_<<endl;
  8. memcpy(beg, &Chars[0], beg_);
  9.  
  10. if(( strlen(Chars)- end_) != 0)
  11.     memcpy(end, &Chars[end_], strlen(Chars)-end_);
  12.    else
  13.        return beg;
  14.  
  15.    char *ret = (char *)malloc(((strlen(beg)+ strlen(end)) + 1 )*sizeof(char));
  16.  
  17.    if(ret == NULL)
  18.     cout << "error buscando memoria\n";
  19.  
  20.    strcat(ret, beg);
  21.    strcat(ret, end);
  22.  
  23.    ret[(strlen(beg)+ strlen(end))] = '\0';
  24.    free(beg);
  25.    free(end);
  26.    return ret;
  27. }
  28.  
  29.  


anteriormente le pasaba un arreglo gigante digas 20kb y la app terminaba con algun error en malloc pero ahora anda bien , pero me gustaria saber que opinan.


Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines