Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CSci 1113: Introduction to C/C++ Programming for Scientists and Engineers Spring

ID: 3710782 • Letter: C

Question

CSci 1113: Introduction to C/C++ Programming for Scientists and Engineers Spring 2018 Homework 9 Due Date: Friday, April 20, 2018 at 6:00pm. Instructions: This is an individual homework assignment. There is one problem worth 20 points. Solve the problem by yourself (unlike the labs, where you can work collaboratively), and submit the solution as a C++ source code file. Here are a few more important details You submit the correct file through Canvas by the due deadline You should follow the example input and output formats given in each problem description. (match the input and output format exactly) Regardless of how or where you develop your solutions, your programs compile and execute on cselabs computers running the Linux operating system . . . Problem: A "Beefier" Book Database This homework will carry on our work on the book database. A solution file for homework 8 is going to be provided, in case you need it. However, you are not required to use this, as long as your own solution is complete and 100% correct as per the requirements of homework 8 1. Program Tasks ("What do I have to do exactly?") In this homework, you will extend your book database in the following way: 1. Split the code into a header (hpp), a source (cpp) and a driver file (containing main0); 2. Perform multiple operations on the book records, described below 3. Use a basic "menu system" to prompt the user for their choice of operation. These are a) Add a new record from keyboard input, to be added to the end of the array of book objects In memory; b) Find a record using the author name (print "record not found" if the record does not exist), and display it on the screen. If there are multiple records that have the same author name, you have to display all those that match; c) Display all records from the input file on the screen; d) Choose a sorting criterion to sort the records, and send them to the output file and to the screen at the same time. Unlike homework 8, we will be not only sorting on book title, but we want to have the ability to sort on any field in the record. That is, the output file can be sorted on author name, or title, or edition, or publication year, or ISBN, or ID. The user wil choose what field he/she wants to sort the records on. Quit the program. e)

Explanation / Answer

// File name: Book.h

#ifndef _BOOK
#define _BOOK
#include <iostream>
#include <string>
#define MAX 2000
using namespace std;

// Class book definition
class book
{
// Data member to store data
string ID, author, title, ISBN;
int edition,yearPublished;
public:
// Prototype of member functions
book();
book(string, string, string, int, int, string);
string getID()const;
void setID(string);
string getAuthor()const;
void setAuthor(string);
string getTitle()const;
void setTitle(string);
int getEdition()const;
void setEdition(int);
int getYear()const;
void setYear(int);
string getISBN()const;
void setISBN(string);

// Friend function prototype
friend ostream& operator<<(ostream&output, book &b1);
friend istream& operator>>(istream&input, book &b1);
friend void Sort(book library[], int size);

// Operational functions
int menu();
void findRecord(book library[], int bookCount);
void writeFile(book library[], int bookCount);
book acceptData();
int readFile(book library[]);
int split(string str, string a[], int max_size);
string nextString(string str, int index);
};// End of class

#endif // End of header file

-------------------------------------------------------------------------------

// File name: Book.cpp
#include <iostream>
#include <string>
#include "book.h"

// Default constructor definition
book::book()
{
// Initialize data members
ID = "no ID";
author = "no author";
title = "no title";
ISBN = "no ISBN";
edition = 0;
yearPublished = 0;
}// End of default constructor

// Parameterized constructor definition
book::book(string id, string Author, string Title, int Edition, int YearPublished, string isbn)
{
// Assigns parameter values to data member of the class
ID = id;
author = Author;
title = Title;
edition = Edition;
yearPublished = YearPublished;
ISBN = isbn;
}// End of parameterized constructor

// Function to return id
string book::getID()const
{
return ID;
}// End of function

// Function to set id
void book::setID(string id)
{
ID = id;
}// End of function

// Function to return author name
string book::getAuthor()const
{
return author;
}// End of function

// Function to set author name
void book::setAuthor(string Author)
{
author = Author;
}// End of function

// Function to return title
string book::getTitle()const
{
return title;
}// End of function

// Function to set title
void book::setTitle(string Title)
{
title = Title;
}// End of function

// Function to return edition
int book::getEdition()const
{
return edition;
}// End of function

// Function to set edition
void book::setEdition(int Edition)
{
edition = Edition;
}// End of function

// Function to return year
int book::getYear()const
{
return yearPublished;
}// End of function

// Function to set year
void book::setYear(int year)
{
yearPublished = year;
}// End of function

// Function to return ISBN
string book::getISBN()const
{
return ISBN;
}// End of function

// Function to set ISBN
void book::setISBN(string isbn)
{
ISBN = isbn;
}// End of function

// Function to overload << operator and returns ostream object
ostream& operator<<(ostream&output, book &b1)
{
output<<b1.ID<<", "<<b1.author<<", "<<b1.title<<", "<<b1.edition<<", "<<b1.yearPublished<<", "<<b1.ISBN;
return output;
}// End of function

// Function to overload >> operator and returns istream object
istream& operator>>(istream&input, book &b1)
{
input>>b1.ID>>b1.author>>b1.title>>b1.edition>>b1.yearPublished>>b1.ISBN;
return input;
}// End of function

void Sort(book library[], int size)
{
// Loops till number of records minus two times
for(int i = 0; i < size; i++)
{
// Loops from outer loop next position to number of records minus one times
for(int j = 0; j < size - i - 1; j++)
{
// Checks i index position of the title with j index position title
if(library[j].getTitle().compare(library[j + 1].getTitle()) > 0)
{
// Swapping process
book temp = library[j];
library[j] = library[j + 1];
library[j + 1] = temp;
}// End of if condition
}// End of inner for loop
}// End of outer for loop
}// End of function

// Function to return next token by splitting str by comma
string nextString(string str, int index)
{
// Stores the length up to the comma
int length = str.find(",", index) - index;
// Returns the substring from the str up to length
return str.substr(index, length);
}// End of function

// Function to return substring up to comma
int split(string str, string a[], int max_size)
{
int n = 0, i = 0;
// Loops string length is not equals to zero and counter i is less than max_size
while((str.length() != 0) && (i < max_size))
{
// Calls the function to extract substring and stores it in a of i index position
a[i] = nextString(str, 0);
// Checks if the substring stored at a of i index position is equals to string str
if(a[i] == str)
{
// Increase the i counter by one
i++;
// Return i
return i;
}// End of if condition
// Otherwise, assigns n to substring stored at i index position length
n = a[i].length() + 1;
// Extracts rest substring
str = str.substr(n, (str.length() - a[i].length() - 1));
// Increase the i value by one
i++;
}// End of while loop
// Returns position
return i;
}// End of function

// Function to display menu and return user choice
int menu()
{
// To store user choice
char choice;
// Displays menu
cout<<" (A) Add Record (F) Find Record by author name";
cout<<" (P) Print All Records (S) Sort Records";
cout<<" (Q) Quit Program"<<endl;
// Accepts user choice
cin>>choice;
// Returns user choice
return choice;
}// End of function

// Function to find a record
void findRecord(book library[], int bookCount)
{
// To store record found status. Initially false for not found
int found = 0;
// To store the author name entered by the user
string author;
// Clears the console input device
fflush(stdin);
// Accepts the author name
cout<<" Enter author name: ";
getline(cin, author);
// Adds space before
author = " " + author;

// Loops till number of records
for(int x = 0; x < bookCount; x++)
{
// Compares current index position author name with author name entered by the user
if(library[x].getAuthor().compare(author) == 0)
{
// Sets the found status to one
found = 1;
// Displays the library book information for found record
cout<<library[x];
}// End of if condition
}// End of for loop
// Checks if the found status is zero then display message record not found
if(found == 0)
cout<<" Record not found.";
}// End of function

// Function to write library array of objects data to file
void writeFile(book library[], int bookCount)
{
// ofstream object declared
ofstream os;
// Opens the file for writing
os.open("bookoutput.txt");
// Checks whether the file can be opened or not
if(os.fail())
{
// Displays error message if unable to open
cout<<" The output file failed to open. Please try again.";
exit(1);
}// End of if condition

// Loops till number of records
for(int i = 0; i < bookCount; i++)
// Writes each object information to the file
os<<library[i]<<endl;
// Close file
os.close();
}// End of function

// Function to accept data
book acceptData()
{
// Declares a temporary object
book book1;
// Temporary variable to store data read from console
int edition = 0;
int year = 0;
// To store string read from console
string bookData;
// To store splitting data
string a[6];
// Clears the console input device
fflush(stdin);
// Accepts book data
getline(cin, bookData);
// Calls the function to split data by comma
split(bookData, a, 6);
// Calls the setter method to assign data to data member of the object book1
book1.setID(a[0]);
book1.setAuthor(a[1]);
book1.setTitle(a[2]);
// To convert the string data to integer
stringstream data(a[3]);
data >> edition;
book1.setEdition(edition);
// To convert the string data to integer
stringstream data1(a[4]);
data1 >> year;
book1.setYear(year);
book1.setISBN(a[5]);
return book1;
}// End of function

// Function to read data from file and stores it in library array of object
// Returns number of records
int readFile(book library[])
{
// To store number of books
int bookCount = 0;
// Temporary variable to store data read from file
int edition = 0;
int year = 0;
// To store string read from the file
string bookData;
// To store splitting data
string a[6];
// ifstream object declared
ifstream is;
// Opens the file for reading
is.open("bookinput.txt");
// Checks whether the file can be opened or not
if(is.fail())
{
// Displays error message if unable to open
cout<<" The input file failed to open. Please try again.";
exit(1);
}// End of if condition

// Loops till end of the file
for(int i = 0; (!is.eof()); i++)
{
// Extracts the first record from the file
getline(is, bookData);
// Checks for not end of file
if(!is.eof())
{
// Calls the function to split data by comma
split(bookData, a, 6);
// Stores the split data to data member using set method
library[i].setID(a[0]);
library[i].setAuthor(a[1]);
library[i].setTitle(a[2]);
// To convert the string data to integer
stringstream data(a[3]);
data >> edition;
library[i].setEdition(edition);
// To convert the string data to integer
stringstream data1(a[4]);
data1 >> year;
library[i].setYear(year);
library[i].setISBN(a[5]);
// increase book counter by one
bookCount++;
}// End of if condition
}// End of for loop
// Close file
is.close();
// Returns record counter
return bookCount;
}// End of function

---------------------------------------------------------------------------------

// File name: BookMain.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <bits/stdc++.h>
#include <iomanip>
#include "book.cpp"
using namespace std;

// main function definition
int main()
{
// Create an temporary object
book book1;
// To store number of books
int bookCount;
// Creates an array of books object of size MAX
book library[MAX];
// Calls the function to read data from file and stores it in array of object
// Return number of records store in bookCount
bookCount = readFile(library);

// Displays the record read from file
cout<<" bookinput.dat contains are below:"<<endl;
// loops till number of records
for(int x = 0; x < bookCount; x++)
// Displays each object information using operator overloading
cout<<library[x]<<endl;
// Displays number of records
cout<<" Database has "<<bookCount<<" records.";

// Loops till user choice is not 'q' or 'Q'
do
{
// Calls the function to display menu and checks return choice
// and calls appropriate function based on user choice
switch(menu())
{
case 'a':
case 'A':
cout<<" Enter the record, with items separated by a comma: ";
library[bookCount] = acceptData();;
bookCount++;
cout<<" Current database size: "<<bookCount<<" records.";
break;
case 'f':
case 'F':
findRecord(library, bookCount);
break;
case 'p':
case 'P':
for(int x = 0; x < bookCount; x++)
cout<<library[x]<<endl;
break;
case 's':
case 'S':
Sort(library, bookCount);
break;
case 'q':
case 'Q':
exit(1);
default:
cout<<" Invalid choice.";
}// End of switch case
}while(1); // End of do while loop
// Calls the function to write library data to file
writeFile(library, bookCount);
return 0;
}// End of main function

Sample Output:

bookinput.dat contains are below:
000001, Bjarne Stroustrup, The C++ Programming Language, 4, 2013, 0321563804
000002, Stephen Colbert, Stephen Colbert's Midnight Confessions, 1, 2017, 1501169009
000003, Tom Clancy, The Hunt for Red October, 2, 1984, 0425240339
000004, Gregory Dudek, Computational Principles of Mobile Robbtics, 2, 2010, 0521692121
000005, Michael Crichton, Airframe, 1, 1995, 0345526775

Database has 5 records.
(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
A

Enter the record, with items separated by a comma: 000007, Pyari Mohan, C Programming, 9, 2018, 5578944652

Current database size: 6 records.
(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
p
000001, Bjarne Stroustrup, The C++ Programming Language, 4, 2013, 0321563804
000002, Stephen Colbert, Stephen Colbert's Midnight Confessions, 1, 2017, 1501169009
000003, Tom Clancy, The Hunt for Red October, 2, 1984, 0425240339
000004, Gregory Dudek, Computational Principles of Mobile Robbtics, 2, 2010, 0521692121
000005, Michael Crichton, Airframe, 1, 1995, 0345526775
000007, Pyari Mohan, C Programming, 9, 2018, 5578944652

(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
s

(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
p
000005, Michael Crichton, Airframe, 1, 1995, 0345526775
000007, Pyari Mohan, C Programming, 9, 2018, 5578944652
000004, Gregory Dudek, Computational Principles of Mobile Robbtics, 2, 2010, 0521692121
000002, Stephen Colbert, Stephen Colbert's Midnight Confessions, 1, 2017, 1501169009
000001, Bjarne Stroustrup, The C++ Programming Language, 4, 2013, 0321563804
000003, Tom Clancy, The Hunt for Red October, 2, 1984, 0425240339

(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
f

Enter author name: Rakesh

Record not found.
(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
F

Enter author name: Pyari Mohan
000007, Pyari Mohan, C Programming, 9, 2018, 5578944652
(A) Add Record (F) Find Record by author name
(P) Print All Records (S) Sort Records
(Q) Quit Program
q