I almost got my user defined string class to work but not quite. When I execute the program, I get a memory error. Code is as follows.
#include <iostream>
using namespace std;
class String {
char *str; //pointer to character block
public:
String();
String (char *s);
void setString (char *s);
int stringLength();
char getString();
};
String::String() {}
String::String(char *s)
{
int length=strlen(s); //length of string
str=new char[length+1]; //increments length of string
strcpy(str,s); //copies s to str
cout<<str<<'\n';
}
void String::setString(char *s)
{
int length=strlen(s); //length of string
str=new char[length+1]; //increments length of string
strcpy(str,s); //copies s to str
cout<<str<<'\n';
}
int String::stringLength()
{
int length=strlen(str);;
return length;
}
char String:: getString()
{
char *s;
int length=strlen(s); //length of string
str=new char[length+1]; //increments length of string
strcpy(str,s); //copies s to str
cout<<str<<'\n';
return *str;
}
int main()
{
String s1="Hello World";
String s2;
s2.setString("THis is a string");
cout<<"string 1 is "<<s1.stringLength()<<"characters long"<< endl;
cout << "string 1 is " << s1.getString()<< endl;
return 0;
}
I think it has to do with my getstring()
function. The reason I have return returning str is because it should be returning my string as shown in the main program. But perhaps I have overlooked something.
Error I get when executed is that memory could not be read.
Thanks in advance.