I have this program that has to accept a string from the user, then a second one and a place to insert the string into the first string. Both strings will be linked lists and i have to insert string 2 into string one where the user asked. The problem i am having is in the function insertafter. It was a worksheet that i had to complete the code, all i was given for the insertafter function was three pointers. I have been looking at it for a while and can't seem to figure out what is causing the problem. It is probably something stupid but i just can't see it. Any help will be most appreciated, thanks.
Code:
#include <iostream>
using namespace std;
struct StringRec
{
char theCh;
StringRec* nextCh;
};
typedef StringRec* StrPtr;
class String
{
public:
String();
~String();
void SetString();
void OutputString();
int GetLength()const;
protected:
StrPtr head;
int strLength;
};
class StringModifier: public String
{
public:
StringModifier();
~StringModifier();
void InsertAfter(StringModifier& subStr, int num);
};
int main()
{
StringModifier str1, str2;
int num = 0;
str1.SetString();
cout<<endl<<"The string before modification: ";
str1.OutputString();
cout<<endl;
str2.SetString();
cout<<"\nEnter place to insert string: ";
cin>>num;
cout<<endl;
str2.OutputString();
cout<<endl;
str1.InsertAfter(str2, num);
cout<<endl;
str1.OutputString();
cout<<endl;
return 0;
}
String::String(): head(NULL), strLength(0)
{
}
String::~String()
{
StrPtr p;
p = head;
while(head != NULL)
{
delete p;
p = NULL;
head = head->nextCh;
p = head;
}
delete p;
p = NULL;
head = NULL;
}
void String::SetString()
{
StrPtr p, last;
char tempCh;
last = head;
cout<<"\nEnter a string: ";
cin.get(tempCh);
while(tempCh != '\n')
{
p = new StringRec;
p->theCh = tempCh;
p->nextCh = NULL;
strLength++;
if(head == NULL)
{
head = p;
last = p;
}
else
{
last->nextCh = p;
last = p;
}
cin.get(tempCh);
}
}
void String::OutputString()
{
StrPtr p;
p = head;
while(p != NULL)
{
cout<<p->theCh;
p = p->nextCh;
}
delete p;
}
int String::GetLength()const
{
return strLength;
}
StringModifier::StringModifier():String()
{
}
StringModifier::~StringModifier()
{
StrPtr p;
p = head;
while(head != NULL)
{
delete p;
p = NULL;
head = head->nextCh;
p = head;
}
delete p;
p = NULL;
}
void StringModifier::InsertAfter(StringModifier& subStr, int num)
{
StrPtr p, q, r;
p = head;
q = subStr.head;
for(int i = 0; i<num; ++i)
{
p = p->nextCh;
}
r = p;
r = r->nextCh;
p->nextCh = q;
while(q != NULL)
{
q = q->nextCh;
}
q->nextCh = r;
}