/* testarr12.cpp CIS 150 06/19/2008 David Klick This program demonstrates how to look up information in parallel arrays. */ #include #include using std::cin; using std::cout; using std::setw; using std::left; void cont(); int main() { int n; const int ARRAY_SIZE = 4; // declare and initialize arrays of names // fname array stores first names // lname array stores last names // These are parallel arrays because the elements // with the same index in each array are related. char fnames[][15] = { "Bob", "Carol", "Ted", "Alice" }; char lnames[][12] = { "Hope", "O'Connor", "Danson", "Springs" }; // loop until user chooses to exit do { // find out which name the user wants to display do { cout << "Display which name? (1-4, -999 to exit) "; cin >> n; if (n == -999) break; if (n<1 || n>4) { cout << "Error: Invalid entry\n"; } } while (n<1 || n>4); // display desired name if user didn't choose to exit if (n != -999) { // actual array entry is 1 less than user entry cout << left << setw(10) << lnames[n-1] << fnames[n-1] << '\n'; } } while (n != -999); cont(); return 0; } /* void cont(); Arguments: none Returns: nothing Clears input buffer and pauses waiting for user to press Enter. */ void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* Sample output: Display which name? (1-4, -999 to exit) 5 Error: Invalid entry Display which name? (1-4, -999 to exit) 2 O'Connor Carol Display which name? (1-4, -999 to exit) 3 Danson Ted Display which name? (1-4, -999 to exit) -999 */