//---------------------------------------------------------------------------- // // FILE : template_example.C // AUTHOR : Eugene Wallingford // CREATION DATE : February 11, 1997 // //---------------------------------------------------------------------------- // // MODIFIED BY : Eugene Wallingford // DATE : September 23, 1997 // DESCRIPTION : Changed program format somewhat for readability // //---------------------------------------------------------------------------- #include // to be able to assert that new worked #include // for standard streams //---------------------------------------------------------------------------- // // CLASS : reader // DESCRIPTION : This template class provides simple prompted input // with range data validation. // //---------------------------------------------------------------------------- template class reader { public: reader(char* prompt); // Constructor TYPE read (TYPE min, TYPE max); // Access message private: char* my_prompt; // Member data object }; //---------------------------------------------------------------------------- template reader::reader(char* prompt) { my_prompt = new char [ strlen(prompt) + 1 ]; // Allocate memory assert( my_prompt != 0 ); strcpy(my_prompt,prompt); // Copy the string } //---------------------------------------------------------------------------- template TYPE reader::read(TYPE min, TYPE max) { TYPE value_to_read; cout << my_prompt << ". " << "The value must be between " << min << " and " << max << ": "; cin >> value_to_read; while ( (value_to_read < min) || (value_to_read > max) ) { cout << endl << endl << "Sorry, but the value must be between " << min << " and " << max << "." << endl; cout << my_prompt << ": "; cin >> value_to_read; } return value_to_read; } //---------------------------------------------------------------------------- // A demonstration program that uses readers of two types. //---------------------------------------------------------------------------- int main () { reader test1("Enter the temperature"); int temp1 = test1.read(0, 100); int temp2 = test1.read(-100, -0); reader test2("Enter your first initial"); char temp3 = test2.read('a', 'z'); char temp4 = test2.read('0', '9'); cout << endl << endl << endl << "1. " << temp1 << endl << "2. " << temp2 << endl << "3. " << temp3 << endl << "4. " << temp4 << endl; } //----------------------------------------------------------------------------