Re: Code Help
Ok, I am getting to mname = "A"; then it crashes but i am getting all
of the file read but there are some random characters and trash thrown
into the output. I am not sure if my getline function or my += and +
functions are not working correctly.
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)
{
if (this == &s)
{
return *this;
}
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] = '\0';
return *this;
}
MyString& MyString :: erase()
{
size = 0;
data[0] = '\0';
return *this;
}
MyString MyString :: operator + (const MyString& s) const
{
MyString addition;
addition = strcat(data, s.data);
addition[size + s.size] = '\0';
return addition;
}
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 + 1] = '\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 + 1] = '\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;
}