I try to reverse a string by pointer walking. Logic is simple that I have two pointers to char one of them head that points to first char of the string. The other tail points to second-last character(before \0) of the string. Swap then char-by-char. C-style it works well, but C++-style doesn't work. I wonder its reason.
C-style
#include <iostream>
#include <cstring>
using std::cin;
using std::cout;
using std::endl;
using std::string;
void reverse(char *str)
{
char *tail, *head;
head = &str[0];
tail = &str[strlen(str)];
cout << "String inverted is: ";
while ((head!=tail)&&(head!=--tail))
{
char temp=*head;
*head++=*tail;
*tail=temp;
}
}
int main(int argc, char const *argv[])
{
char str[100];
cout << "Enter a string: ";
cin.getline(str,100);
reverse(str);
cout << str;
cout <<"\n";
return 0;
}
C++-style
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
void reverse(string str)
{
char *tail, *head;
head = &str[0];
tail = &str[str.size()];
cout << "String inverted is: ";
while ((head!=tail)&&(head!=--tail))
{
char temp=*head;
*head++=*tail;
*tail=temp;
}
}
int main(int argc, char const *argv[])
{
string str;
cout << "Enter a string: ";
getline(cin,str);
reverse(str);
cout << str;
cout <<"\n";
return 0;
}
std::reverse(str.begin(), str.end());but C++-style doesn't workCare to explain that? Also you should be using iterators to modify the string and not pointers into the strings data.