#Help in String class

6 messages · Page 1 of 1 (latest)

random ferry
#

I'm trying to make custom string class,
everything is working fine in this but when i take input then it is not printing any line after that it just ends the program

#include<bits/stdc++.h>
using namespace std;

class String
{
    char *ch;            // buffer
    unsigned int len;    // to store the length
    public:
    // default constructor
        String() : ch(nullptr) , len(0){};

    // parametrized constructor
    String(const char *str)
    {
        len = strlen(str+1);
        ch = new char[len+1];
        strcpy(ch,str);      // (to , from)
    }


    // copy constructor
    String(const String& str)
    {
        this->ch = str.ch;
        len = strlen(ch+1);
    }

    // assignment operator overloading
    String &operator=(String str)
    {
        if(this->ch != str.ch)
        {
            Swap(*this,str);
        }
        return *this;
    }

    void Swap(String &a, String &b){
        std::swap(a.ch,b.ch);
        std::swap(a.len,b.len);
    }

    friend ostream &operator<<(ostream &out , const String &str);
    friend istream &operator>>(istream &in ,  String &str);
};


ostream &operator<<(ostream &out , const String &str)
{
    out<<str.ch;
    return out;
}

istream &operator>>(istream &in , String &str)
{
    in>>str.ch;
    return in;
}

int main()
{
    String myString = "hello";
    // cin>>myString;
    cout<<myString<<endl;
    String sty ;
    sty = myString;
    cout<<sty<<endl;
    String hup;
    cin>>hup;
    cout<<hup<<endl;
}

wooden marshBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

random ferry
#

plz mention

frail panther
#

@random ferry you should take this question to #1013107104678162544 instead.

#

I've not looked to carefully, but could it be that internally your String class is not null-terminated?
If so then you may need something like this instead

ostream &operator<<(ostream &out , const String &str)
{
    out.write(str.ch, str.len);
    // you may still want to append the null terminator here though?
    return out;
}
#

Your input stream looks wrong too.
You cannot just stream to a char*.

Without cheating via istream::getline() you'd have to read ahead in the stream to find the null terminator, do the memory allocation to however many bytes you skipped ahead to get there, and then play catch-up from the rear to actually read the string into yours.