// Source: "Software Design ...", John A Robinson, Newnes, 2004, page 138. #include #include using namespace std; int error(char *p) { cerr << p << "\n"; return 0; } class String { char *buf; int len; // Length does not include terminating '\0' public: // Constructors String (const char *p) // String x("abc"); { len = strlen(p); buf = new char[len + 1]; strcpy(buf, p); } String () { buf = new char; buf[0] = 0; len = 0;} // String x; // Note that String of length 0+1 created, so that delete buf // will work correctly when the destructor is called. // Destructor ~String() { delete [] buf;} // Assignment to and from Strings String& operator=(const char *p); // x = "abc"; String& operator=(const String &str); // y = x; char& operator[](int i); // c = x[4]; x[5] = 'a'; friend ostream& operator<<(ostream& out, const String &x); friend istream& operator>>(istream& in, String &x); // Tests friend int operator==(const String &x, const char *s) { return (strcmp(x.buf, s) == 0); } friend int operator==(const String &x, const String &y) { return (strcmp(x.buf, y.buf) == 0); } friend int operator!=(const String &x, const char *s) { return (strcmp(x.buf, s) != 0); } friend int operator!=(const String &x, const String &y) { return (strcmp(x.buf, y.buf) == 0); } friend int strlen(const String &x) { return x.len; } }; String& String::operator=(const char *p) { // Delete old String delete [] buf; len = strlen(p); buf = new char[len + 1]; strcpy(buf, p); return *this; } String& String::operator=(const String &str) { if (str.buf != buf) // Protect against x = x; { delete [] buf; len = str.len; buf = new char[len + 1]; strcpy(buf, str.buf); } return *this; } char& String::operator[](int i) { if (i < 0 || i >= len) { error("index out of range"); i = 0; } return buf[i]; } ostream& operator<<(ostream& out, const String &x) { return out << x.buf; } istream& operator>>(istream&in, String &x) { char tempbuf[256]; // Set maximum number of chars to read in.width(256); // And get a whitespace-separated word in >> tempbuf; // Copy string over x = tempbuf; return in; } main() { String st[100]; int n; cout << "Enter several lines of text:\n"; for (n = 0; n < 100; n++) { cin >> st[n]; String test; cout << (test = st[n]) << '\n'; for (int j=0; j < n; j++) // Search for a match { if (st[j] == test) cout << "Seen before at line " << j << '\n'; } if (test == "done") break; } cout << "Here are the input lines in reverse order, with modifications\n"; for (int i=n-1; i >= 0; i--) { st[i][i] = 'X'; cout << st[i] << '\n'; } return 0; }