I wrote the following program to do string manipulation using
overloaded operators! See the code first then I explain the error! (It
might be a bit too long)
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
class string
{
private:
char * str;
int len;
public:
string();
string(char *);
friend string operator + (const string &, const string &);
friend string operator - (const string &, const string &);
void display(void)
{
cout<<str<<endl<<endl;
}
};
string :: string ()
{
len = 0;
str = "";
}
string :: string (char * a)
{
len = strlen (a);
str = new char [len + 1];
strcpy(str,a);
}
string operator + (const string & T, const string & S)
{
string temp;
temp.len = T.len + S.len;
temp.str = new char [temp.len + 1];
strcpy(temp.str, T.str);
strcat(temp.str, S.str);
return (temp);
}
string operator - (const string & T, const string & S)
{
string temp;
char * substr;
substr = strstr(T.str,S.str);
if (substr == NULL)
{
cout<<"Substring not found! ";
return(temp);
}
else if (substr == T.str)
{
temp.len = T.len-S.len;
temp.str = new char [temp.len + 1];
strcpy(temp.str,T.str);
strnset(temp.str,' ',S.len);
strrev(temp.str);
temp.str[temp.len] = '\0';
strrev(temp.str);
}
else
{
temp.len = strlen(T.str);
temp.str = new char [temp.len + 1];
strcpy(temp.str,T.str); //HERE IS WHERE IT ALL HAPPENS
strrev(temp.str);
strnset(temp.str ,' ',S.len);
strrev(temp.str);
}
return (temp);
}
void main()
{
clrscr();
char * tmp_str = new char [30];
char * tmp_str2 = new char [30];
cout<<"Enter string 1: ";
gets(tmp_str);
cout<<"Enter string 2: ";
gets(tmp_str2);
string S1(tmp_str), S2(tmp_str2), S3, S4, S5;
delete []tmp_str;
delete []tmp_str2;
S3 = S1 + S2;
S4 = S3 - S1;
S5 = S3 - S2;
cout<<endl<<endl;
cout<<"S1: ";S1.display();
cout<<"S2: ";S2.display();
cout<<"S3 = S1 + S2: ";S3.display();
cout<<"S4 = S3 - S1: ";S4.display();
cout<<"S5 = S3 - S2: ";S5.display();
getch();
}
If i give the input:
String 1: Hello(no space)
String 2: World(one space before world)
output is:
S1: Hello
S2: World
S3: Hello World
S4: World
S5: Hello
Perfect.
If I give this input:
String 1: Hello (space)
String 2: World (Space or no space before world)
output is:
S1: Hello
S2: World
S3: Nothing is printed (which should this be affected?)
S4: World
S5: Nothing is printed
the error mesg sub string not found is also displayed...
I've declared in the function headers S3 as const (T in the
functions), which means it shouldn't be changed within the functions.
The whole thing baffled me! When i inspected it, i found out that S3,
is changed as I copy it's string into temp. Why? To this point i've
failed to understand why that happens! Whoever can, just please take
your time to check it out!