// This is my solution to Assignment 4 -- Kent #include #include #include #include #include struct book { char *title; int pages; float cost; }; // book const int MAXBOOKS=30; // Function headers int page_count( struct book ** , int); float cost_count( struct book ** , int); void print_books( struct book ** , int); int main(int argc, char **argv) { int actual_count = 0; char yn='y'; struct book **books; // pointer to array of book structures pointers struct book **bptr; // used to print the array char buffer[1024]; // buffer for title input // make the space for an array of book pointers if( (books = new struct book * [MAXBOOKS]) == NULL) { // there was no space available cout << "Not enough memory for the book pointer array" << endl; exit(1); } while(actual_count < MAXBOOKS) { // first make space for the book if( (books[actual_count] = new struct book) == NULL) { // there was no space available cout << "Not enough memory for the actual book structure" << endl; exit(1); } // get the data from the user cout << "Please enter the book title: "; cin >> buffer; if( (books[actual_count]->title = new char [strlen(buffer)+1]) == NULL) { // there was no space available cout << "Not enough memory for the book title" << endl; exit(1); } (void) strcpy(books[actual_count]->title,buffer); cout << "Please enter the number of pages: "; cin >> books[actual_count]->pages; cout << "Please enter the cost: "; cin >> books[actual_count]->cost; actual_count++; cout << "do you want to enter another? (y/n) "; cin >> yn; if( (tolower(yn) != 'y')) // tolower() changes its arg to lowercase break; } // while print_books(books,actual_count); cout << "--------------------------" << endl; cout << "Total books: " << actual_count << endl; cout << "Total pages: " << page_count(books,actual_count) << endl; cout << "Total cost: " << cost_count(books,actual_count) << endl; delete [] books; return 0; } // main /* Using a pointer, go over the array of book structures printing the contents of each one */ void print_books( struct book ** books, int count) { int i; struct book **bptr; // a for loop is used to not only control the pointer // but to make sure we don't go pas the last book for(i = 0,bptr=books; i < count; i++,bptr++ ) { cout << "book number: " << i << endl; cout << "title: " << (*bptr)->title << endl; cout << "pages: " << (*bptr)->pages << endl; cout << "cost: " << (*bptr)->cost << endl; cout << endl; } // for } // print_books // Add up the total count of pages int page_count( struct book ** books, int count) { int total_pages = 0; for(int i = 0; i < count; i++ ) total_pages += books[i]->pages; return(total_pages); } // page_count // Add up the total cost of all books float cost_count( struct book ** books, int count) { float total_cost = 0.0; for(int i = 0; i < count; i++ ) total_cost += books[i]->cost; return(total_cost); } // page_count