Help with reversing string
Mar 25, 2014 at 1:22am UTC
i cannot use pointers and i have to ask the user to enter it and store into an array, then replace the content of the string in reverse and save into another array, and finally print the original and reversed string in the function.
here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
void rev_str ()
{
int x;
char std[81];
char revstd[81];
cout << "please enter a string: " ;
cin >> std;
x = sizeof (std);
for (int i = 0; i < x ; i++)
{
std[i] = revstd[i];
}
for (int j = x - 1; j >= 0; j--)
{
cout << std[j];
}
}
Mar 25, 2014 at 2:59am UTC
From
http://www.cplusplus.com/faq/sequences/arrays/sizeof-array/
Firstly, the sizeof() operator does not give you the number of elements in an array, it gives you the number of bytes a thing occupies in memory.
And since arrays are static they always have the same size(in your case 81).
Instead you could try iterating over the array until you find the null character ('\0') and that would give you the size you wanted
Mar 25, 2014 at 3:00am UTC
Have you tried using a stack or are you creating a new string?
Mar 25, 2014 at 6:05am UTC
Reversing a string can be done in-place:
http://ideone.com/oQ7oP7
In your case, the only thing you are missing is the actual reversing process
Last edited on Mar 25, 2014 at 6:11am UTC
Topic archived. No new replies allowed.