I think you want something like this:
#include<ctype.h>
class AlphaString
{
public:
AlphaString( char *ch );
~AlphaString();
private:
char *_text;
size_t sizeOfText;
};
AlphaString::AlphaString( char *ch )
: _text(0),sizeOfText(0)
{
if(ch)
{
size_t numberOfCharacters = 0;
char* ptr = ch;
while(*ptr)
{
char c = *ptr;
if(isalpha(c))
{
numberOfCharacters++;
}
ptr++;
}
if(numberOfCharacters)
{
_text = new char[numberOfCharacters+1];
char* ptrSource = ch;
char* ptrDestination = _text;
while(*ptrSource)
{
char c = *ptrSource;
if(isalpha(c))
{
*ptrDestination = c;
ptrDestination++;
}
ptrSource++;
}
_text[numberOfCharacters] = '\x0';
sizeOfText = numberOfCharacters;
}
}
}
This should work :) - you can use your own destructor implementation ...
This constructor addresses a few important points:
1. Initialization of member variables:
_text(0),sizeOfText(0)
C++ does not initialize member variables, that’s something you have to perform yourself.
2.
if(ch)
tests if
ch
is not NULL – if it is, the original code is in trouble
3. count the number of alphabetic characters
4. if there are any alphabetic characters - allocate the required amount of memory:
number of alphabetic characters + 1 (for terminating zero)
5. copies
only the alphabetic characters to the allocated buffer
6. zero terminates the buffer
Regards
Espen Harlinn