0

I have a custom string class that uses an array of chars,

class MyString
{

private:
int length; 
char *chars; 

public:
MyString(const char* input)
{
    length = 0; 
    while (input[length] != '\0')
        ++length;

    chars = new char[length + 1];

    for (int j = 0; j < length; j++)
        chars[j] = input[j];
}  

However when I use this class with a simple output I am getting a strange result in the console:

MyString newStr = "Test";
cout << newStr; 

Gives me this output in the console:

Test═²²²²½½½½½½½½■ε■ε■ε■

This is with Visual Studio 2010 Win32 console app. I don't really know c++ very well and this is my first try at it.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
sean
  • 91
  • 2
  • 8

3 Answers3

2

You forgot to put \0 at the end of chars[]. \0 is the character that MUST be put at the end of a char sequence. Otherwise, your program will output some random stuff (the bits after your array in memory) until it finds a \0.

Hilydrow
  • 918
  • 1
  • 6
  • 15
2

Your loop that copies input to chars isn't including the NUL terminator. Change the loop condition to j <= length and it should work.

Daniel Gallagher
  • 6,915
  • 25
  • 31
1

There are a couple of things that I'd recommend:

  1. You are not null terminating your chars[]
  2. you need to overload the << operator. Go to: http://www.fredosaurus.com/notes-cpp/oop-friends/overload-io.html for an example.
David Weiser
  • 5,190
  • 4
  • 28
  • 35