jeudi 18 mars 2021

How to Write a Custom Read function for my Custom String Class

Hi i am trying to better understand how the standard string class works and so writing a very simple custom string class. The following are my class' members:

class String {
public:
   String() : first_elem(nullptr), first_free(nullptr), cap(nullptr) { }
   CustomString(const String&);//copy constructor
   CustomString(std::initializer_list<char>);
   std::size_t size();
   std::size_t capacity();
   char * begin() const;
   char * end() const;
   void push_back(const char &ch){
check_and_allocate();
    alloc.construct(last_elem++,ch);
};
   void pop_back();
private:
 char * first_elem;
 char * last_elem;
 char * cap;
 static std::allocator<char> alloc;


};

There are many more member functions that i have and the class is working fine but now i am trying to implement a read() function that will read data(characters) from console into the String object. This is what i have tried so far:

std::istream& read(std::istream &is, String& obj){
     char ch;
     while(is >> ch and ch!='\n'){
         obj.push_back(ch);
     }
    

    return is;
}

I also have a member function to dynamically check and allocate according to if the object is full and reallocate using std::move. But i don't think my read() function is working. It is a friend function. Also the program is working but not correctly that is when i type something on the console and hit enter the while loop doesn't break . How can i obtain the desired result. String class has elements of type char. How can i read characters from console until end-of-file or the user hit enter and then add them(using push_back()) to the String object? I am calling the read() function from my main.cpp files as read(std::cin, mystringobject);

Aucun commentaire:

Enregistrer un commentaire