custom string exercise in c++
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 m开发者_运维知识库e 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.
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
.
Your loop that copies input
to chars
isn't including the NUL terminator. Change the loop condition to j <= length
and it should work.
There are a couple of things that I'd recommend:
- You are not null terminating your chars[]
- you need to overload the << operator. Go to: http://www.fredosaurus.com/notes-cpp/oop-friends/overload-io.html for an example.
精彩评论