String reverse

Hi,

Below is my code to reverse a string. But when I am printing the reverse of a string it is coming out to be empty. Can somebody please help me?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>
#include <string>

using namespace std;
int main()
{
int j=0;
string str;
string rstr;
cout<<"\n Enter the string:";
getline(cin,str);

for(int i =str.length()-1; i>=0; i--)
{	rstr[j] = str[i];
	j++;
}
cout<<"\n The reverse of a string is:"<<rstr;

return 0;
}
rstr starts out as the empty string, so the rstr[j] values are all invalid. You need to adjust it to the proper size before trying to edit its values.
http://www.cplusplus.com/reference/string/string/resize/
got it.. thanks..
Topic archived. No new replies allowed.