// This is my solution to Assignment 4 using arrays- Kent #include #include #include #include #include struct book { char *title; int pages; float cost; }; // book const int MAXBOOKS=30; struct book Books[MAXBOOKS]; // array of book structures // function headers float cost_count(int); int page_count(int); void print_books(int); int main(int argc, char **argv) { int actual_count = 0; char yn='y'; char buffer[1024]; // buffer for title input while(actual_count < MAXBOOKS) { // 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(actual_count); cout << "--------------------------" << endl; cout << "Total books: " << actual_count << endl; cout << "Total pages: " << page_count(actual_count) << endl; cout << "Total cost: " << cost_count(actual_count) << endl; return 0; } // main /* go over the array of book structures printing the contents of each one */ void print_books(int count) { for(int i = 0; i < count; i++) { cout << "book number: " << i << endl; cout << "title: " << Books[i].title << endl; cout << "pages: " << Books[i].pages << endl; cout << "cost: " << Books[i].cost << endl; cout << endl; } // for } // print_books // Add up the total count of pages int page_count(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(int count) { float total_cost = 0.0; for(int i = 0; i < count; i++ ) total_cost += Books[i].cost; return(total_cost); } // page_count