Can't reverse the inputted characters

Sample Output:

Type word(s): hello
The reverse is 'olleh'.

The problem is, I can't get it reversed. Please help... Here is my code...

#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char orig [300];
char rev [300];
int len;
void original ()
{
cout << "\n\n\tType word(s): ";
cin.getline (orig,300);
}
void reversed ()
{
int x = 0;
int y = len;
for (x=0;x<y;x++)
{
rev [x]=orig [y-x];
}
}
void main ()
{
clrscr ();
original ();
len = strlen (orig);
reversed ();
cout << "\n\n\tThe reverse is: '" << rev << "'.";
getch ();
}
Hi!

Suppose we wish that the text length is 10 character. So the the first character starts from 0 (zero) index and the text is stored till 9th index.
ABCDEFGHIJ text lays in memory like this:


orig[0] <- A
orig[1] <-B
.
.
.
orig[9]<- J

Now see your code:
1
2
3
4
5
int x = 0;
int y = len;
for (x=0;x<y;x++)
{
rev [x]=orig [y-x];


In the last command variable y is 10 (if the length of the text is 10), x is 0, so you want to put data from orig[10-0] to rev[0]. So orig[10] is (I think) 0.
If a string array starts 0 value, it means it is an empty text.

You should change your code like this:
rev [x]=orig [y-x -1];


Alternatively, look at STL string and the reverse algorithm.

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

http://www.cplusplus.com/reference/algorithm/reverse/
thanks you very much screw!...
Last edited on
Topic archived. No new replies allowed.