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.

2
  • Your first try should be with a book, do you have one? Commented Jan 18, 2011 at 2:20
  • 1
    You haven't shown the code that outputs the string. Show that. Commented Jan 18, 2011 at 2:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.