I am trying to write my own getline function and it keeps on segfaulting. How do I fix it and how does get line work officially if mine is not functional? I am writing this to learn how to code better.
#include"MyString.h"
MyString::MyString( ) //constructor
{
size=0;
capacity=1;
data=new char[capacity];
}
MyString::MyString(char * n) //copy constructor
{
size=strlen(n);
capacity=strlen(n)+1;
data=new char[capacity];
strcpy(data,n);
}
MyString::MyString(const MyString &right) //
{
size=strlen(right.data);
capacity=strlen(right.data)+1;
data=new char [capacity];
strcpy(data,right.data);
}
MyString::~MyString( )
{
delete [] data;
}
MyString MyString::operator = (const MyString& s)
{
if(this!=&s)
{
MyString temp=data;
delete [] data;
size=strlen(s.data);
capacity=size+1;
data= new char [capacity];
strcpy(data,s.data);
}
}
MyString& MyString::append(const MyString& s)
{
if(this!=&s)
{
strcat(data,s.data);
}
}
MyString& MyString::erase()
{
}
MyString MyString::operator + (const MyString& s)const
{
return strcat(data,s.data);
}
bool MyString::operator == (const MyString& s)
{
return strcmp(data,s.data)==0;
}
bool MyString::operator < (const MyString& s)
{
return strcmp(data,s.data)<0;
}
bool MyString::operator > (const MyString& s)
{
return strcmp(data,s.data)>0;
}
bool MyString::operator <= (const MyString& s)
{
return strcmp(data,s.data)<=0;
}
bool MyString::operator >= (const MyString& s)
{
return strcmp(data,s.data)>=0;
}
bool MyString::operator != (const MyString& s)
{
return strcmp(data,s.data)!=0;
}
void MyString::operator += (const MyString& s)
{
append(s.data);
}
char& MyString::operator [ ] (int n)
{
return data[n];
}
void MyString::getline(istream& in)
{
char c;
erase();
ifstream input;
while(in.get(c)&&c!='\n')
{
data[size]=c;
size++;
if(size+1<=capacity)
{
capacity*=2;
char*p=new char[capacity];
strcpy(p,data);
delete [] data;
data=p;
}
data[size]=c;
size++;
data[size]='\0';
}
}
int MyString::length( ) const
{
return strlen(data);
}
void MyString::grow()
{
capacity=strlen(data)+1;
MyString temp;
temp=data;
delete [] data;
capacity*=2;
data= new char[capacity];
}
ostream& operator<<(ostream& out, MyString& s)
{
out<<s.data;
return out;
}
// int MyString::getCapacity(){return capacity;}
It should look something like this:
Now you just need to properly implement a method called append that appends a single character. If you have trouble with that, then ask another question. You may think I’m being facetious here, but I am not. You need to limit the places that you reallocate and stop repeating yourself in your code. A getline function is not the place for that sort of activity (reallocations, I mean).