string class

What am I doing wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>

using namespace std;

class String {
        int size;
        char * buffer;
        int strlen(const char *s)
        {
            for(int i = 0; s[i] != '/0'; i++)
                return i;
        }
public:
        String();
        String(const String & s);
        String(const char *p);
        ~String();
        int length();

	// other methods

        friend bool operator==(const String &, const String &);
        friend bool operator<=(const String &, const String &);
        friend bool operator<(const String &, const String &);
        friend ostream & operator<<(ostream &, const String &);
};

String::String()
{
    buffer = 0;
    size = 0;
}

String::String(const String & s)
{
    size = s.size;
    buffer = new char[size];
    for(int i =0; i < size; i++)
    {
        buffer[i] = s.buffer[i];
    }
}

String::String(const char *p)
{
    size = strlen(p);
    buffer = new char[size];
    for(int i = 0; i < size; i++)
    {
        buffer[i] = p[i];
    }
}

int String::length()
{
    return size;
}


String::~String()
{

}

ostream & operator<<(ostream &os, const String &s)
{
    os << String(s);
    return os;
}



#include <cassert>

using namespace std;

int main()
{
   String s1; // s1 == ""
   assert(s1.length() == 0);

   String s2("hi");  // s2 == "hi"
   cout << s2;
   //assert(s2.length() == 2);
}


I believe there's something wrong with my
ostream & operator<<(ostream &os, const String &s)

But there might be more errors in this code. It compiles but then crashes when ran.
Last edited on
closed account (D80DSL3A)
You must allow space for a terminating null '\0' in your string object.
1
2
3
4
5
6
7
8
9
10
String::String(const char *p)
{
    size = strlen(p);
    buffer = new char[size+1];// one extra for the '\0'
    for(int i = 0; i < size; i++)
    {
        buffer[i] = p[i];
    }
    buffer[size] = '\0';// assign as last element
}

Yes, there is a problem in operator<<
Instead of os << String(s);// a constructor returns nothing. Not even void!
Do this: os << s.buffer;
The destructor needs work too.
A few minor bugs:
1
2
3
4
5
6
        int strlen(const char *s)
        {
            int i=0;
            for( i = 0; s[i] != '\0'; i++){}
            return i;
        }

Note the \0 instead of /0 and also you want to finish the for loop before you return i
In the operator <<, use os << s.buffer;
Thanks it all works perfectly now. Now to continue this until I get more of the string class working.
Topic archived. No new replies allowed.