Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: Saberuneko en 28 Mayo 2012, 17:16 pm



Título: Trasteando con Strings (C++)
Publicado por: Saberuneko en 28 Mayo 2012, 17:16 pm
Hola, llevaba un tiempo ya trasteando con C, y ya tengo cierto nivel, no me defiendo mal, así que decidí comenzar hoy con C++, mi primer experimento, ha sido ponerme a trastear con las funciones de strings, algo nuevo para mí, ya que en C esto se maneja con arrays de caracteres.

El comienzo no ha estado mal, pero me he atascado un poquito:
Este es mi código completo:

Código
  1. //"Toying around with strings and vars"
  2.  
  3. #include <iostream>
  4. #include <string>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. //declaring strings and vars
  10. string str1, str2, str3;
  11. char testchar1;
  12. int count, pos;
  13.  
  14. //setting initial strings
  15. str1 = "This is a test String";
  16. str2 = "One";
  17.  
  18. //playing with size instructions
  19. cout << "Size: " << str1.size() << endl;
  20. cout << "Capacity: " << str1.capacity() << " (Before reserve)" << endl;
  21. str1.reserve(64);
  22. str2.reserve(64);
  23. cout << "Capacity: " << str1.capacity() << " (After reserve)" << endl;
  24.  
  25. //Toying with 'at' instruction
  26. cout << "Chars per position:" << endl;
  27. cout << "--" << endl;
  28. for (size_t count=0; count < str1.length(); count++)
  29. {
  30. cout << "[" << count << "] -> " << str1.at(count) << endl;
  31. }
  32.  
  33. cout << "\n";
  34.  
  35. //Testing append instruction
  36. cout << "str1 contains: " << str1 << endl;
  37. cout << "str2 contains: " << str2 << endl;
  38. str2.append(4,'-');
  39. str2.append("Two");
  40. cout << "Now, str2: " << str2 << endl;
  41.  
  42. //Swapping the content of str1 and str2
  43. str1.swap (str2);
  44. cout << "After a swap: \n";
  45. cout << "str1 contains: " << str1 << endl;
  46. cout << "str2 contains: " << str2 << endl;
  47.  
  48. //Experimenting with find and substr
  49. pos = str1.find("String");
  50. str3 = str1.substr (pos);
  51.  
  52. cout << "I found the word: " << str3 << endl;
  53. cout << "It starts at position: " << pos << endl;
  54.  
  55. //Trying out string comparison:
  56. //int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 )
  57. if (str3.compare(0,6,str2,14,6))
  58. cout << "Found " << str3 << " into " << str1 << endl;
  59.  
  60. if (str1.compare(0,3,str3,0,6))
  61. cout << "Weird... I found " << str2 << " into " << str3 << "!\n";
  62. else
  63. cout << "Didn't find " << str2 << " into " << str3 << endl;
  64.  
  65. return 0;
  66. }

La ejecución ha ido bien hasta un punto cercano al final, aquí muestro el retorno en consola:

Código:
Size: 21
Capacity: 21 (Before reserve)
Capacity: 64 (After reserve)
Chars per position:
--
[0] -> T
[1] -> h
[2] -> i
[3] -> s
[4] ->
[5] -> i
[6] -> s
[7] ->
[8] -> a
[9] ->
[10] -> t
[11] -> e
[12] -> s
[13] -> t
[14] ->
[15] -> S
[16] -> t
[17] -> r
[18] -> i
[19] -> n
[20] -> g

str1 contains: This is a test String
str2 contains: One
Now, str2: One----Two
After a swap:
str1 contains: One----Two
str2 contains: This is a test String

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Viendo dónde se ha quedado clavado, el problema parece estar en alguna parte del código después del comentario:
Código:
//Experimenting with find and substr

Mi compilador (Dev-C++) ya no me da errores, así que no se me ocurre qué puedo haber hecho mal...

¿Me echáis una mano? Lo estoy pasando muy bien trasteando, y tengo curiosidad por saber en qué fallé, y si hay alguna manera algo mejor de usar alguna de las instrucciones que me han funcionado aquí.

Un Saludo, y miauchísimas gracias por adelantado. :3


Título: Re: Trasteando con Strings (C++)
Publicado por: Ferno en 28 Mayo 2012, 17:35 pm
¿No faltan parámetros en el método find?

http://www.cplusplus.com/reference/string/string/find/

Es lo que pude encontrar, y no estoy bien afilado con C++. Además, si el compilador no te dio problemas es probable que no sea este el problema. Pero buen, es una idea.


Título: Re: Trasteando con Strings (C++)
Publicado por: Saberuneko en 29 Mayo 2012, 08:15 am
Ya veo, si, ese find falla, lo comenté para que lo ignorase el programa y la ejecución seguía (aunque tampoco como lo planeé exactamente, voy a seguir experimentando a ver si le pillo el truco.

Gracias por la ayuda. :3