Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does get line work?
    text
    copied!<p>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.</p> <pre><code>#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 &amp;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&amp; s) { if(this!=&amp;s) { MyString temp=data; delete [] data; size=strlen(s.data); capacity=size+1; data= new char [capacity]; strcpy(data,s.data); } } MyString&amp; MyString::append(const MyString&amp; s) { if(this!=&amp;s) { strcat(data,s.data); } } MyString&amp; MyString::erase() { } MyString MyString::operator + (const MyString&amp; s)const { return strcat(data,s.data); } bool MyString::operator == (const MyString&amp; s) { return strcmp(data,s.data)==0; } bool MyString::operator &lt; (const MyString&amp; s) { return strcmp(data,s.data)&lt;0; } bool MyString::operator &gt; (const MyString&amp; s) { return strcmp(data,s.data)&gt;0; } bool MyString::operator &lt;= (const MyString&amp; s) { return strcmp(data,s.data)&lt;=0; } bool MyString::operator &gt;= (const MyString&amp; s) { return strcmp(data,s.data)&gt;=0; } bool MyString::operator != (const MyString&amp; s) { return strcmp(data,s.data)!=0; } void MyString::operator += (const MyString&amp; s) { append(s.data); } char&amp; MyString::operator [ ] (int n) { return data[n]; } void MyString::getline(istream&amp; in) { char c; erase(); ifstream input; while(in.get(c)&amp;&amp;c!='\n') { data[size]=c; size++; if(size+1&lt;=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&amp; operator&lt;&lt;(ostream&amp; out, MyString&amp; s) { out&lt;&lt;s.data; return out; } // int MyString::getCapacity(){return capacity;} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload