// File: simpleStringTest.cpp // Tests the simpleString class #include "simpleString.h" #include using namespace std; //default constructor simpleString::simpleString() { cerr << "***** default constructor *****" << endl; capacity = INITIAL_CAPACITY; contents = new char[capacity]; length = 0; } //destructor simpleString::~simpleString() { cerr << "***** destructor *****" << endl; delete [] contents; } //copy constructor simpleString::simpleString (const simpleString & s) { cerr << "***** copy constructor *****" << endl; capacity = s.capacity; contents = new char[capacity]; length = s.length; for (int i = 0; i < length; i = i + 1) contents[i] = s.contents[i]; } //assignment operator const simpleString & simpleString::operator= (const simpleString & rhs) { cerr << "***** assignment operator *****" << endl; if (this != &rhs) { delete [] contents; capacity = rhs.capacity; contents = new char [capacity]; length = rhs.length; for (int i = 0; i < length; i = i + 1) contents[i] = rhs.contents[i]; } return *this; } // Member functions // Read a simple string void simpleString::readString() { char next; // the most recent character read from cin int pos = 0; // the number of characters in contents cin.get (next); while ((next != '\n') && (pos < MAX_CAPACITY)) { if (pos >= capacity) expandCapacity(); contents[pos] = next; pos = pos + 1; cin.get (next); } length = pos; if (pos == MAX_CAPACITY) cerr << "WARNING: Reached maximum capacity of a simpleString." << endl; } // Display a simple string void simpleString::writeString() const { for (int i = 0; i < length; i = i + 1) cout << at (i); } // Retrieve the character at a specified position // Returns the character \0 if position is out of bounds. char simpleString::at(int pos) const { if ((pos < 0) || (pos >= length)) return '\0'; else return contents[pos]; } // Return the string length int simpleString::getLength() const { return length; } // Expands the capacity by some positive amount. void simpleString::expandCapacity() { const int EXPANSION_FACTOR = 2; const int EXPANSION_MINIMUM = 1; int newCapacity = EXPANSION_FACTOR * capacity + EXPANSION_MINIMUM; char * newContents = new char [newCapacity]; for (int i = 0; i < capacity; i = i + 1) newContents[i] = contents[i]; capacity = newCapacity; delete [] contents; contents = newContents; }