Problem:
When you attempt to do operations like string *pName = &name
and
string *pNameLast = &name + nChar - 1;
, you're treating std::string
's as char*
's. You cannot do that and expect the code to work.
Solution:
Treat std::string
's as std::string
's. Instead of doing string *pName = &name
declare pName
as an int
and use the operator []
of std::string
to access to the values. Similarly with pNameLast
. You also have to declare string save
as a char
or, as I prefer, use the std::swap
function.
Additional info:
- As far as I can see you're probably using
using namespace std;
as you're declaring std::string
as string
. If that is the case consider that using namespace std;
is considered a bad practice (More info here).
Full code:
#include <iostream>
int main() {
std::string name = "george";
int length = name.size();
int pNameFirst = 0;
int pNameLast = length - 1;
while(pNameFirst < pNameLast)
{
std::swap(name[pNameFirst],name[pNameLast]);
pNameFirst++;
pNameLast--;
}
std::cout << name << std::endl;
}