How to correct an output of "hello!²²²²▌▌▌▌▌▌mc₧m▌☺"?

  c++

Basically, I’m writing a function append a char to char*, but for unknown reason it does not work…

I searched around stackoverflow, there are similar questions but I’m not allowed to write the code with <string.h> library…

Thus could anyone point out my error? Highly appreciated for any responses!

Below is my function that causes error:

C_String C_String::operator + (const char& c) const
{
    int size = this->length() + 2;
    char* updated_buffer = new char[size];

    for (int i = 0; this->buffer[i] != '{$content}'; i++)
    {
        updated_buffer[i] = this->buffer[i];
    }
    updated_buffer[size - 2] = c;
    updated_buffer[size - 1] = '{$content}';

    C_String result = C_String(updated_buffer);
    return result;
}

//the constructor used within the function
C_String::C_String(const char* c)
{
    int size = 0;
    if (c)
    {
        for (int i = 0; c[i] != '{$content}'; i++)
        {
            size++;
        }
    }
    size++;

    if (c)
    {
        this->buffer = new char[size];
        for (int i = 0; c[i] != '{$content}'; i++)
        {
            this->buffer[i] = c[i];
        }
        this->buffer[size-1] = '{$content}';
    }
    else
    {
        this->buffer = nullptr;
    }
}

Below is my test code:

int main()
{
    CMPT135_String a = CMPT135_String("hello");
    char c = '!';
    cout << a + c << endl; //this outputs "hello!²²²²▌▌▌▌▌▌mc₧m▌☺"
    cout << a << endl; //this outputs "hello" which is fine

    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT