C++/CharBuffer
Expert: vijayan - 4/17/2011
Question"I want to design & implement a CharBuffer
class, particularly handle character stream for storage. The class is special in the sense
that it used special character “#” as marker for adding any segment of characters. The
read requests also follow these markers.
initially i try to make it and help me further.
Thanks
class CharBuffer{
private:
char * CData;
unsigned int max; // maximum size of buffer
unsigned int wInd; // read index
unsigned int rInd; // write index
public:
CharBuffer();
CharBuffer(unsigned int m);
CharBuffer(const CharBuffer & rhs);
~CharBuffer();
CharBuffer& operator=(const CharBuffer & rhs);
char* readCharBuffer();
void writeCharBuffer(char* data);
};"
LOOK THE EXAMPLE BELOW
CharBuffer CB1= new CharBuffer(5000);
CB1.Write("I am rafi");
CB1.Write("I am fien here");
The data inside object appears as " I a rafi#I am fine here#.........."
the read index is at 0, and the write index is at 24. the maximum
capacity of CB1 is 5000.
Answer> CharBuffer CB1= new CharBuffer(5000);
Create a char buffer this way:
CharBuffer CB1(5000);
In the constructor CharBuffer::CharBuffer(unsigned int m), dynamically allocate memory (using new[]) for m chars, in the destructor release the memory with delete[], do a deep copy in the copy constructor and a deep assignment in the overloaded assignment operator.
See
http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/
and
http://www.fredosaurus.com/notes-cpp/oop-condestructors/shallowdeepcopy.html
for information on how to do this.
In addition to
char * CData;
unsigned int max; // maximum size of buffer
unsigned int wInd; // read index
unsigned int rInd; // write index
you would also need to keep track of how much of the current buffer is used. For example, add
unsigned int used; // number of characters in the used part of the buffer
For void CharBuffer::writeCharBuffer(char* data);
a. determine the number of chars in data, say N, with std::strlen
b. verify that wInd + N is less than max
c. copy data into the buffer with std::strcpy( CData + wInd, data ) ;
d. append a '#' at the end with cData[wInd+N] = '#' ;
e. add N+1 to wInd
f. if wInd is greater than used, update used