Home > Software design >  Overloading istream operator
Overloading istream operator

Time:11-02

I have a String class. I want to overload operator >>. Found the following way, but as far as I understand, the zero character is not added at the end (line terminator). How can I write a good operator >>?

class String {
 public:
  char* str;
  size_t size;
  size_t capacity;

  ~String();
  String(const char*);
  friend std::istream& operator>>(std::istream&, String&);
};

std::istream& operator>>(std::istream& is, String& obj) {
      is.read(obj.str, obj.size);
      return is;
    }

CodePudding user response:

Let's start with the obvious part: your operator>> needs to actually create a valid String object based on the input you read. Let's assume you're going to read an entire line of input as your string (stopping at a new-line, or some maximum number of characters).

For the moment, I'm going to assume that the str member of any String is either a null pointer, or a pointer to data that's been allocated with new.

std::istream &operator>>(std::istream &is, String &obj) { 
    static char buffer[max_size];

    is.getline(buffer, max_size);
    std::size_t size = std::strlen(buffer);
    if (size > 0) {
        if (size > obj.size) {
            delete [] obj.str;
            obj.str = new char [size 1];
            obj.capacity = size;
        }
        strcpy(obj.str, buffer);
        obj.size = size;
    }
    return is;
}

That isn't intended to handle every corner case (e.g., it has no error handling), but at least gives sort of the general idea--you'll need to read in the text, check that you have enough space to store the text, allocate more if needed, copy the text into the (existing or newly allocated) space, and update at least the size to the current size, and if you reallocated, the capacity to the updated capacity as well.

  • Related