No output

Expected output:
Hi
Hi samir
But the program gives no output .Please explain me why is this happening?
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
#include <iostream>
#include<string.h>
using namespace std;

class String
{
    char *c;
    int length;
public:
    String(){length=0;c=new char[2];strcpy(c,'\0');}
    String(char *p){length=strlen(p);c=new char[length+1];strcpy(c,p);}
//    String(const String &p){length=strlen(p);c=new char[length+1];strcpy(c,p);}
    String operator+(String &p)
    {
        String s;
        s.c=strcat(c,p.c);
        return s;
    }
    bool operator==(String &p)
    {
        if(!strcmp(c,p.c))
            return true;
    }
    void showdata()
    {
        cout<<"hi "<<*c<<endl;
    }
    ~String(){delete c;}
};
int main()
{
    String s;
    String s1("samir");
    s.showdata();s1.showdata();
    return 0;
}
try

cout<<"hi "<<c<<endl; //*c is a single character. cout understands char* to be a string type

and fix this bug

strcpy(c,'\0');}

strcpy takes a c-string, not a single character ('\0' is one character).
instead just use c[0] = 0; (or type 4 chars for 1 if you pref '\0')

the forum compiler gave your expected results with those changes.
Last edited on
Thanks a lot
Also note that your operator+ needs to allocate extra space to concatenate the string.
Topic archived. No new replies allowed.