/* testarr14.cpp CIS 150 06/19/2008 David Klick This program demonstrates how to search for information in parallel arrays, with the array data coming from a data file. */ #include #include #include using std::cin; using std::cout; using std::setw; using std::left; using std::ifstream; void cont(); int find(int id[], int length, int idnum); int main() { int n, pos; int numrecs = 0; // number of array elements being used const int ARRAY_SIZE = 100; // must leave more space than needed // declare arrays of names and IDs char names[ARRAY_SIZE][40]; int id[ARRAY_SIZE]; // open file containing name and ID data ifstream infile("arraydata.txt"); if (!infile) { cout << "Error: Could not open input file\n"; cont(); return 1; } // load arrays from file infile >> id[0]; while (infile && numrecs> id[numrecs]; } } infile.close(); // loop until user chooses to exit do { // find out which ID # the user wants to display cout << "Find which user id? (-999 to exit) "; cin >> n; // display desired name if user didn't choose to exit if (n != -999) { pos = find(id, ARRAY_SIZE, n); if (pos == -1) { cout << "Error: ID number not found\n"; } else { // display names associated with ID # cout << setw(3) << n << ": " << names[pos] << '\n'; } } } while (n != -999); cont(); return 0; } /* int find(int id[], int length, int idnum); Arguments: int id[]: holds employee ID numbers int length: number of elements in id[] array int idnum: employee number to search for Returns: an integer indicating the position in the id[] array where idnum was found, or -1 if idnum was not found Searches for an ID number within an array of ID numbers and returns the position where found, or -1 if not found. */ int find(int id[], int length, int idnum) { int i; for (i=0; isungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* Sample output: Find which user id? (-999 to exit) 5 Error: ID number not found Find which user id? (-999 to exit) 99 99: Bob Hope Find which user id? (-999 to exit) 27 27: Carol O'Connor Find which user id? (-999 to exit) 32 32: Ted Danson Find which user id? (-999 to exit) 18 18: Alice Springs Find which user id? (-999 to exit) -999 Listing of data file: 99 Bob Hope 27 Carol O'Connor 32 Ted Danson 18 Alice Springs */