Reputation: 20901
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;
}
Upvotes: 0
Views: 578
Reputation: 4812
You are not passing the string in to reverse
by reference.
You are currently passing in a copy of the string.
make reverse
have this prototype:
void reverse(string& str)
Upvotes: 4