Search code examples
c++operator-overloadingcindynamic-arraysistream

How to new a dynamic array after cin


I'm trying to make a class that contains a pointer, which is the core of a dynamic array. How to overload the operator >> so I can cin >> to the pointer without know how many characters are going to put? I was trying:

#include <iostream>
class MyString
{
private:
    char* str;
    size_t length;

public:
    //some code here

    friend std::istream& operator>>(std::istream& is, const MyString& other)
    {
        is >> other.str;
        return is;
    }
}

and this happened when I try to cin a string: HEAP CORRUPTION DETECTED

Is there a way to read a string, assign it to my string, and won't use the std::string header? (I was trying to make a string class that doesn't depend on std::string)


Solution

  • A naive implementation would use is.get() to retrieve one character at a time, and append it to other, resizing if needed. And stop when std::isspace(chr) is true, of course. For that, you need to dynamically allocate memory and keep track of how much space you are using / have available in the implementation of MyString.

    Here is the skeleton for that; you probably need to implement the append() method.

    friend std::istream& operator>>(std::istream& is, MyString& other) {
       while (true) {
          int chr = is.get();
          if (is.eof() || std::isspace(chr)) {
              break;
          }
          other.append((char)chr);
       }
       return is;
    }