I am having difficulty with class objects. I cannot figure out 1. why my program won't actually compare the two strings. 2. why and where I am having a memory dump crash. Any and all help would be helpful since I have completely confused myself. The following is my main.cpp, String.cpp, and the header file in that order.
#include <iostream>
usingnamespace std;
#include "GREEN_String.h"
void main ()
{
GREEN_String Str1;
GREEN_String Str2 ("AdrianGreen");
GREEN_String Str3 (Str2);
GREEN_String Str4 ("isstumped");
cout << "This is a Test display of the third String: " << endl;
Str3.Display ();
cout << "This is a Test display of my programs ability to copy Strings: " << endl;
Str1.Copy (Str2);
Str4.Copy (Str4);
Str1.Display ();
Str4.Display ();
cout << "The difference between these two strings is: " << Str1.Compare (Str2) << endl;
cout << "The difference between these two strings is: " << Str3.Compare (Str1) << endl;
Str1.Concat (Str3);
Str3.Concat (Str4);
cout << "This is a test display of my programs ability to concatenate strings: " << endl;
Str1.Display ();
Str3.Display ();
}
this will set the pChar of the current GREEN_String's instance to a new char array of length [Length+1]
if pChar was pointing to a valid array before this then the instance loses this previous value upon the assignment statement and also causes a memory leak.
you could rectify this method but would be more efficient to simply remove it and allow the constructor that accepts a char array to cater for using the version of the Compare method that accepts a GREEN_String object.
Hmm, I understand your point "Sik," However, I was told that I hate to cater to both entries and would need two different Methods. To be really honest, I have done classes for less than a week and have really confused myself.
Also, note. My code has been edited. Thank you "ne555."
I see problems with both of your Concat() functions which would cause a crash.
You need to allocate enough space to pChar for both char arrays to be copied into.
In the 1st version Concat (const GREEN_String & Str) I think you want something like:
1 2 3 4 5
char * pTemp = pChar;// save pointer to old block
pChar = newchar[NumChars + Str.NumChars + 1];// enough for both strings
strcp(pChar, pTemp);// copy old block into new block
delete [] pTemp; // now you can release the old block
strcat (pChar, Str.pChar);// add 2nd string to 1st
Similarly for the 2nd version, Concat (const char Chars[]).
This 2nd version could actually handle both cases. Simply call Concat(Str.pChar); from the 1st version.
What is the line while ((Size = cin.get ()) != '\0') for? There should be no console input there. Is this an effort to debug the crash?