reversing a string

Hi all,

I want to reverse a string using pointers. So, i wrote the program as follows,

1. string s;
2. s="abed";
3. str=strewn(s);
4. char *p;
5. p=&s;
6. for( int i=0;i<str; i++) {
7. cout << *p;
8. p++;
9. }


It gave me a compile-time error in the line 5 (p=&s) saying 'string cannot be assigned to char pointer'. Now, please anyone tell me how to print the string using pointers.

thanks,
aras

use a char* for string s instead of a string and you wont have that problem
Don't use C strings if you can avoid it/aren't using C. If you want to reverse an std::string, you can use the std::reverse() function:

reverse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <algorithm>
#include <iostream>
#include <string>

int main()
{
	std::string buffer;

	std::cout << "Enter a string to see it in reverse: ";
	std::getline(std::cin, buffer);

	std::reverse(buffer.begin(), buffer.end());

	std::cout << buffer << std::endl;

	return 0;
}
Topic archived. No new replies allowed.