Hello!

I am writing a program to overload ~ operator to reverse the given string.
Here is my program.
The problem message is that"Could not find a match for string::string(char).
I am writing my program on linux. I can not use strrev function.

#include<iostream.h>
#include<string.h>
class String
{
char str[20];
int count;

public:

String ()
{}


String (char*str1)
{
int i=0;
strcpy(str,str1);
while(str[i++]!='\0')
count++;
}

void operator~ ()
{
int j=0;
String str2[20];
for(int i=count;i>=0;i--)
str2[j++]=str[i];      //the problem is here.*****************
str2[j]='\0';
//return str2;
}

};

int main()
{
String s1("hello");
String s2();
~s1;
return 0;
}

Hello!

I am writing a program to overload ~ operator to reverse the given string.
Here is my program.
The problem message is that"Could not find a match for string::string(char).
I am writing my program on linux. I can not use strrev function.

#include<iostream.h>
#include<string.h>
class String
{
char str[20];
int count;

public:

String ()
{}


String (char*str1)
{
int i=0;
strcpy(str,str1);
while(str[i++]!='\0')
count++;
}

void operator~ ()
{
int j=0;
String str2[20];
for(int i=count;i>=0;i--)
str2[j++]=str[i];      //the problem is here.*****************
str2[j]='\0';
//return str2;
}

};

int main()
{
String s1("hello");
String s2();
~s1;
return 0;
}
String str2[20];

Why are you creating 20 String objects here? That's setting aside 400 characters of storage, isn't it? You only need 20 at the most, right? So if you want to have 20 characters worth of temporary storage, set aside one String object or 20 characters, but not 20 String objects.

you only need to swap the first half with the second. The terminating value for the loop shouldn't be zero. It should be half of count, or something like that. I'd do it by counting j up rather than counting i down, but you should get the drift. And you need to have a temporary holding variable before you assign one to the other, otherwise you loose the original value of the element you have assigned to.

This article has been dead for over six months. Start a new discussion instead.