Wrong text console output when using overloaded operators

47 Views Asked by At

I made this program with a class who has a buffer called word and saves strings passed to it using the overloaded operator '+'. It works well, but in the output there are corrputed bytes. I don't find where is the problem.

#include <cstdlib>
#include <iostream>
using namespace std;

class text {
   const char *word;
   int size;
   public:
   text(int sz);
   text(const text &cpytxt);
   ~text() { delete [] word; }
   text &operator+(const char *str);
   void operator!();
   void operator--();
};

text::text(int sz = 80) {
   if(sz <= 0) {
      cout << "Error: sz <= 0" << '\n';
      exit(1);
   }

   size = sz;
   word = new char[sz];
}

text::text(const text &cpytxt) {
   if(cpytxt.size <= 0) {
      cout << "Error: cpytxt.size <= 0" << '\n';
      exit(1);
   }

   size = cpytxt.size;
   word = new char[cpytxt.size];
}

text &text::operator+(const char *str) {
   char *tmpstr = (char *) str; // Saves constant direction into non-constant direction for later usage
   char *tmpwrd = (char *) word; // Same with the object buffer
   
   int i = 0; // Creates 'i' iterator

   while(*tmpwrd) { // Sets word direction and 'i' poiting to the last empty byte
      ++tmpwrd;
      ++i;
   }

   // Assigns each char from the string to the last empty byte of word and consecutive empty bytes
   for(; i < size && *tmpstr; ++i, ++tmpwrd, ++tmpstr) { 
      if(i == size - 1) *tmpwrd = '\0';
      else *tmpwrd = *tmpstr;
   }

   return *this; // Returns invoking object
}

void text::operator!() { 
   cout << word;
}

void text::operator--() {
   char *tmpwrd = (char *) word;

   for(int i = 0; i < size; ++i, ++tmpwrd) {
      *tmpwrd = '\0';
   }
}

int main() {
   
   text myTxt(1000);

   myTxt + "Hello World!" + " This is an example!";
   !myTxt;
   --myTxt;
   myTxt + "GOODBYE!";
   !myTxt;
   --myTxt;

   system("pause");
   return 0;
}

Program output

Changing the constructor and overloaded operator function to add a '\0' at the beginning of the word buffer and at the end respectively.

0

There are 0 best solutions below