Re: Code Help
Ok, I have worked a lot of the kinks out but on the driver which is
posted above when fname = fname; for some reason trash gets put into
it even though before this fname is holding Bob but after this call it
holds trash.
Here is my updated functions.cpp
#include "MyString.h"
#include <iostream>
#include <cstdlib>
using namespace std;
MyString :: MyString()
{
size = 0;
capacity = size + 1;
data = new char[capacity];
data[0] = '\0';
}
MyString :: MyString(char * s)
{
size = strlen(s);
capacity = size + 1;
if (size >= capacity)
{
grow();
}
data = new char[capacity];
strcpy(data, s);
data[size] = '\0';
}
MyString :: MyString (const MyString& s)
{
size = s.size;
capacity = size + 1;
if (size > capacity)
{
grow();
}
data = new char[capacity];
strcpy(data, s.data);
data[size] = '\0';
}
MyString :: ~MyString()
{
delete []data;
}
MyString MyString :: operator =(const MyString& s)
{
delete [] data;
size = s.size;
capacity = size + 1;
if (size >= capacity)
{
grow();
}
data = new char[capacity];
strcpy(data, s.data);
data[size] = '\0';
return *this;
}
MyString& MyString :: append (const MyString& s)
{
size += s.size;
capacity = size + 1;
if (size >= capacity)
{
grow();
}
strcat(data, s.data);
data[size + 1] = '\0';
return *this;
}
MyString& MyString :: erase()
{
size = 0;
data[0] = '\0';
return *this;
}
MyString MyString :: operator + (const MyString& s) const
{
MyString result( *this );
result.append( s );
return result;
}
bool MyString :: operator == (const MyString& s)
{
if (strcmp(data, s.data) == 0)
{
return true;
}
else
{
return false;
}
}
bool MyString :: operator < (const MyString& s)
{
if (strcmp(data, s.data) < 0)
{
return true;
}
else
{
return false;
}
}
bool MyString :: operator > (const MyString& s)
{
if (strcmp(data , s.data) > 0)
{
return true;
}
else
{
return false;
}
}
bool MyString :: operator <= (const MyString& s)
{
if (strcmp(data, s.data) <= 0)
{
return true;
}
else
{
return false;
}
}
bool MyString :: operator >= (const MyString& s)
{
if (strcmp(data, s.data) >= 0)
{
return true;
}
else
{
return false;
}
}
bool MyString :: operator != (const MyString& s)
{
if (!strcmp(data, s.data))
{
return true;
}
else
{
return false;
}
}
void MyString :: operator += (const MyString& s)
{
size += s.size;
capacity = size + 1;
if (size >= capacity)
{
grow();
}
strcat(data, s.data);
data[size] = '\0';
}
char& MyString :: operator [] (int n)
{
return data[n];
}
void MyString :: getline (istream& in)
{
size = 0;
char c;
in.get(c);
while(c != '\n' && in)
{
data[size] = c;
size++;
if (size >= capacity)
{
grow();
}
in.get(c);
}
data[size] = '\0';
}
void MyString :: grow()
{
char *temp;
temp = data;
capacity *= 2;
data = new char[capacity];
strcpy(data, temp);
data[size] = '\0';
delete [] temp;
}
int MyString :: length () const
{
return size;
}
ostream& operator<< (ostream& out, MyString& m)
{
out << m.data;
return out;
}