This is my code:
#include <iostream>
#include <cstring>
using namespace std;
void invertidor (char cadena[], int tamano)
{
int tamano2=tamano;
char invertido[tamano2];
for (int x=0, y=tamano; x<tamano && y>=0; x++, y--)
{
invertido[x]=cadena[y];
}
cout<<"> "<<cadena<<endl;
cout<<endl<<"> "<<invertido<<endl<<endl;
return;
}
int main ()
{
char opcion;
string palabra;
int longitud, longitud2;
while (opcion!='n')
{
system ("cls");
cout<<"> Ejercicio 6"<<endl<<endl;
cout<<"> Ingrese una palabra: ";
cin>>palabra;
longitud=palabra.length();
char cadena[palabra.size()+1];
strcpy(cadena, palabra.c_str());
longitud2=strlen(cadena);
invertidor (cadena,longitud2);
cout<<"> Desea hacer una nueva operacion? (s/n): ";
cin>>opcion;
if (opcion=='n')
{
exit(0);
}
}
return 0;
}
My problem is that the inverted word does not appear at the end.
Why use an array and not directly a String
Your code doesn't work because it doesn't take into account the
c
end of string character'\0'
. Being the first character that you invert... well, a string of length 0 will always appear (even if the rest is later) ;-)Although the answer is already solved, the easiest solution is to use iterators:
All the best.
Your code doesn't work because it hits the loop, do this
try with this code
It is convenient to use the standard library specific functions, reverse() and reverse_copy(). For example:
Since this is an exercise for a student, it is convenient that you have more than one way to do it. This is another one, using other simple constructions. I put a pre-initialized string to make it easier to experiment with. The string returned by the function should be freed at the end when it is no longer needed.
This is another alternative. In this case, the investment is made in-situ, without creating another chain. The index is made to move from both ends of the string towards the center. There is a small optimization in the function
invert()
for the case of strings with an odd number of characters.This way you can make it interactive in a short way.