#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class String
{
private:
char* s;
int size;
public:
String()
{
s = NULL;
size = 0;
}
String(const char* str)
{
size = strlen(str);
s = new char[size];
for (int i = 0; i < size; i++)
s[i] = str[i];
}
String(const String& obj)
{
size = obj.size;
s = new char[size];
for (int i = 0; i < size; i++)
s[i] = obj[i];
}
String(int x)
{
size = x;
s = new char[size];
}
char& operator[](int i)
{
return *(s + i);
}
const char operator[](int i) const
{
return *(s + i);
}
String& operator+(const char& str) // append a char at the end of string
{
int newsize = size + 1;
String newstr(size);
for (int i = 0; i < size; i++)
{
newstr.s[i] = s[i];
}
newstr.s[size] = str;
delete[]s;
s = newstr.s;
size = newsize;
return *this;
}
String& operator+(char*& str) // append a string at the end of string
{
int newsize = size + strlen(str);
String newstr(newsize);
for (int i = 0; i < size; i++)
{
newstr.s[i] = s[i];
}
for (unsigned i = 0; i < strlen(str); i++)
{
newstr.s[size + i] = str[i];
}
delete[]s;
s = newstr.s;
size = newsize;
return *this;
}
operator int() const
{
int m;
m = size;
return m;
}
};
int main()
{
String s1("abcd");
String s2;
s2 = s1 + 'e';
cout << s2[3];
cout << s2[4];
char* c = (char*)"asdfgh";
s2 = s1 + c;
cout << s2[3];
cout << s2[4];
cout << s2[8];
}
My code runs perfectly until the statement char* c = (char*)"asdfgh"
. After this statement, I am not getting actual output. s2[3]
after the statement char* c = (char*)"asdfgh"
is supposed to give 'd'
in the output, and similarly s2[4]
is supposed to give 'a'
in the output, and s2[8]
is supposed to give 'g'
in the output. But, the problem is, when I run this program, I am not getting these actual values.
Kindly look into this and tell me where I need to make changes.