#include <iostream>
using namespace std;
class Customer
{
public :
string email, name, address;
long telephoneNo;
int addNew()
{
cout<<"Enter the email, name, address and telephone no. of the user Please.\n";
cin>>email>>name>>address>>telephoneNo;
return 0;
}
int edit()
{
cout<<"Enter new name, email, address and telephone no. of user Please.\n";
cin>>email>>name>>address>>telephoneNo;
return 0;
}
int update()
{
cout<<"Enter new email, address and telephone no. of user Mr./Ms. "<<name<<" Please.\n";
cin>>email>>address>>telephoneNo;
return 0;
}
};
class Order : public Customer
{
public :
static int number;
const float price = 10000.0;
float payment;
string state, billingAddress;
bool created, paymentMade;
Customer *customer;
Order(Customer *customer)
{
number++;
this->customer = customer;
payment = price + (0.1f*price);
state = "West Bengal";
billingAddress = customer->address;
created = true;
paymentMade = false;
}
int setState(string state)
{
this->state = state;
return 0;
}
float getPrice()
{
return price;
}
};
int Order::number = 0;
class Passenger : public Order
{
public :
string name;
bool insurance, priorityBoarding;
float luggage, extraLuggage;
Order *order;
Passenger(Order *order)
{
char flag;
this->order = order;
name = order->customer->name;
cout<<"Enter the luggage amount for the customer Mr./Ms. "<<name<<", in kgs Please.\n";
cin>>luggage;
if(luggage > 15.0)
extraLuggage = luggage - 15.0f;
cout<<"Is the customer eligible for insurance. y/n? \n";
cin>>flag;
if(flag == 'y')
insurance = true;
else
insurance = false;
cout<<"Is the customer a priority boarder. y/n? \n";
cin>>flag;
if(flag == 'y')
priorityBoarding = true;
else
priorityBoarding = false;
}
Passenger get()
{
return *this;
}
int edit()
{
char flag;
cout<<"Please re-enter the name of the Passenger.\n";
cin>>name;
cout<<"Enter the luggage amount for the customer Mr./Ms. "<<name<<", in kgs Please.\n";
cin>>luggage;
if(luggage > 15.0)
extraLuggage = luggage - 15.0f;
cout<<"Is the customer eligible for insurance. y/n? \n";
cin>>flag;
if(flag == 'y')
insurance = true;
else
insurance = false;
cout<<"Is the customer a priority boarder. y/n? \n";
cin>>flag;
if(flag == 'y')
priorityBoarding = true;
else
priorityBoarding = false;
return 0;
}
int update()
{
char flag;
cout<<"Enter the luggage amount for the customer Mr./Ms. "<<name<<", in kgs Please.\n";
cin>>luggage;
if(luggage > 15.0)
extraLuggage = luggage - 15.0f;
cout<<"Is the customer eligible for insurance. y/n? \n";
cin>>flag;
if(flag == 'y')
insurance = true;
else
insurance = false;
cout<<"Is the customer a priority boarder. y/n? \n";
cin>>flag;
if(flag == 'y')
priorityBoarding = true;
else
priorityBoarding = false;
return 0;
}
};
class OrderFlight : public Order, public Passenger
{
public :
static int flights;
Passenger* passenger;
int addPassenger(Order *order)
{
Passenger* passenger = new Passenger(&order);
this->passenger = passenger;
return 0;
}
int removePassanger()
{
delete(&passenger);
return 0;
}
/*
float getPrice(Passenger *passenger)
{
Passenger* gPassenger = Passenger::get();
}
*/
};
int OrderFlight::flights = 50;
int main()
{
cout<<"Hello World";
return 0;
}
Getting the error ---
In constructor ‘Passenger::Passenger(Order*)’:
main.cpp:84:5: error: no matching function for call to ‘Order::Order()’
I am trying to send a pointer of the object of class Order in the constructor of Passenger, but getting this error instead. Did the same thing while passing the object or Order in the addPassenger() method of the OrderFlight class but did not get any error. Please help.
class Passenger : public Order says that a Passenger is an Order. That doesn't really make sense, and ultimately is the source of your error:
Part of constructing a Passenger involves constructing all of its base classes, which includes Order. However, Order does not have a default constructor, and you do not use a delegating constructor to tell it how to construct the Order part of itself, so it doesn't know what to do.
I would rethink your inheritance hierarchy here. Like what I mentioned above, class Order : public Customer doesn't make sense because it implies that Orders are Customers. class OrderFlight : public Order, public Passenger also doesn't make sense for the same reason.
Related
I have a test class where I have all my test cases for my java project, I want to initialize the service class once which creates an array and I want to use the same array for all the other test cases, I have tried to do that but when the first test case is ran an customer is registered and stored in the array I want to use the customer stored in the array and use it for the next test case but it seems that the customer is not in the array for the next test case i.e a new array is being created or I think that junit is running each test case individually
MainTests.java
package tests;
import static org.junit.Assert.*;
import org.junit.*;
import services.BankingServiceImpl;
import dao.BankingSystemArrayImpl;
public class MainTests {
static BankingServiceImpl bankingService;
private static boolean setupIsDone = false;
#BeforeClass
public static void setup() {
bankingService = new BankingServiceImpl();
}
#Test // 1
public void createCustomer() {
String custName = "Rohan";
String HomeAddressCity = "Pune";
String HomeAddressState = "Maharashtra";
int HomeAddressPincode = 411043;
String LocalAddressCity = "Pune";
String LocalAddressState = "Pune";
int LocalAddressPincode = 411043;
int day = 19;
int month = 9;
int year = 1998;
int result = bankingService.acceptCustomerDetails(custName, HomeAddressCity, HomeAddressState,
HomeAddressPincode, LocalAddressCity, LocalAddressState, LocalAddressPincode, day, month, year);
System.out.println(bankingService.getLength());
assertTrue(result > 0);
}
#Test // 2
public void openCustomerAccount() {
System.out.print(bankingService.getLength());
int customerid = 100;
int balance = 100000;
String accountType = "savings";
int result = bankingService.openAccount(customerid, balance, accountType);
assertTrue(result > 0);
}
#Test // 3
public void Balance() {
int customerid = 100;
int accountid = 50;
int pin = 1007;
int result = bankingService.getAccountBalance(customerid, accountid, pin);
assertTrue(result > 0);
}
#Test // 4
public void amt_withdraw() {
int customerid = 100;
int accountid = 50;
int amount = 10000;
int pin = 1007;
int result = bankingService.withdraw(customerid, accountid, amount, pin);
assertEquals(result, 90000);
}
#Test // 5
public void transfer() {
int customerid = 100;
int accountid = 50;
int customerid1 = 101;
int accountid1 = 51;
int amount = 10000;
int pin = 1007;
boolean result = bankingService.fundTransfer(customerid, accountid, customerid1, accountid1, amount, pin);
assertEquals(result, true);
}
#Test // 6
public void amt_deposit() {
int customerid = 100;
int accountid = 50;
int amount = 10000;
int result = bankingService.deposit(customerid, accountid, amount);
assertEquals(result, 90000);
}
/*
* #Test //7 public void cust_details() { int customerid = 100;
* BankingServiceImpl bankingService = new BankingServiceImpl();
*
* int result = bankingService.getCustomerDetails(customerid);
* assertEquals(result, 90000); }
*/
#Test // 10
public void pin_change() {
int customerid = 100;
int accountid = 50;
int o_pin = 1007;
int n_pin = 1122;
boolean result = bankingService.changePin(customerid, accountid, o_pin, n_pin);
assertEquals(result, true);
}
#Test // 11
public void check_change() {
int customerid = 100;
int accountid = 50;
int pin = 1007;
boolean result = bankingService.checkPin(customerid, accountid, pin);
assertEquals(result, true);
}
}
Service Class
package services;
import beans.Account;
import beans.Address;
import beans.Customer;
import beans.MyDate;
import beans.Transaction;
import dao.BankingSystemArrayImpl;
public class BankingServiceImpl {
BankingSystemArrayImpl BankingSystemArray;
public BankingServiceImpl() {
System.out.print("called");
BankingSystemArray = new BankingSystemArrayImpl();
}
/*
* public void transfer(int accountId, int tansferAccountId, double amount)
* { double a = BankingSystemArray.getAccount(accountId).getBalance()
* - amount; System.out.println(a);
* BankingSystemArray.getAccount(accountId).setBalance(a); double b =
* BankingSystemArray.getAccount(accountId).getBalance() + amount;
* BankingSystemArray.getAccount(tansferAccountId).setBalance(b);
*
* }
*/
public int acceptCustomerDetails(String custName, String HomeAddressCity,
String HomeAddressState, int HomeAddressPincode,
String LocalAddressCity, String LocalAddressState,
int LocalAddressPincode, int day, int month, int year) {
if ((day > 0 && day <= 31) && (month >= 1 && month <= 12)
&& (year <= 2015)) {
return BankingSystemArray.insertCustomer(new Customer(
custName, new Address(LocalAddressCity, LocalAddressState,
LocalAddressPincode), new Address(HomeAddressCity,
HomeAddressState, HomeAddressPincode), new MyDate(
day, month, year)));
} else
return 0;
}
public int openAccount(int custId, int balance, String accType) {
int accountId = 0;
if (custId < 99) {
System.out
.println("Invalid customer Id,please enter a valid customer Id");
} else if (!(accType.equalsIgnoreCase("savings")
|| accType.equalsIgnoreCase("current") || accType
.equalsIgnoreCase("salary"))) {
System.out
.println("Invalid account type, please enter a valid account type");
} else if (balance < 0) {
System.out.println("Invalid amount, please amount a valid amount");
}
else {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer == null) {
System.out.println("Sorry you have not registered");
return 0;
} else {
Account account = new Account(accType, balance);
accountId = BankingSystemArray.insertAccount(account,
custId);
}
}
return accountId;
}
public int getAccountBalance(int custId, int accNo, int pin) {
if (checkPin(custId, accNo, pin)) {
return BankingSystemArray.getAccount(custId, accNo)
.getBalance();
} else {
System.out.println("Invalid pin");
return 0;
}
}
public int withdraw(int custId, int accNo, int amt, int pin) {
int balance = 0;
if (amt < 0) {
System.out.println("Invalid amount, please enter a valid amount");
} else {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer == null) {
return 0;
} else {
Account account = BankingSystemArray.getAccount(custId,
accNo);
if (account == null) {
System.out.println("Sorry your account does not exist");
} else if (account.getPin()!=pin) {
System.out.println("Invalid pin");
return 0;
} else {
if ((account.getBalance() - amt) > 0) {
account.setBalance(account.getBalance() - amt);
balance = account.getBalance();
}
}
}
}
return balance;
}
public boolean fundTransfer(int custIdFrom, int accNoFrom, int custIdTo,
int accNoTo, int amt, int pin) {
if (withdraw(custIdFrom, accNoFrom, amt, pin) > 0) {
deposit(custIdTo, accNoTo, amt);
return true;
}
return false;
}
public int deposit(int custId, int accNo, int amt) {
if (amt < 0) {
System.out.println("Invalid amount, please enter a valid amount");
} else {
BankingSystemArray.getAccount(custId, accNo).setBalance(
BankingSystemArray.getAccount(custId, accNo)
.getBalance() + amt);
return BankingSystemArray.getAccount(custId, accNo)
.getBalance();
}
return 0;
}
public Customer getCustomerDetails(int custId) {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer != null) {
return customer;
}
return null;
}
public Account getAccountDetails(int custId, int accNo) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
return account;
}
return null;
}
public Account[] getAllAccountsDetails(int custId) {
Account[] account = BankingSystemArray.getAccountList(custId);
if (account != null) {
return account;
}
return null;
}
public Transaction[] getAllTransactionDetails(int custId, int accNo) {
// TODO Auto-generated method stub
return null;
}
public int generatePin(int custId, int accNo) {
Account account = BankingSystemArray.getAccount(custId, accNo);
int pin = BankingSystemArray.generateRandomNumber();
account.setPin(pin);
return account.getPin();
}
public boolean changePin(int custId, int accNo, int oldPin, int newPin) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
if (account.getPin() == oldPin) {
account.setPin(newPin);
return true;
}
}
return false;
}
public boolean checkPin(int custId, int accNo, int pin) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
if (account.getPin() == pin) {
return true;
}
}
return false;
}
public Customer getLength() {
return BankingSystemArray.getLength();
}
}
To solve your problem, you need first to understand the JUnit behavior.
Methods marked with #BeforeClass and #AfterClass are run only
once, and are the upper and lower bound of all your test methods.
Methods marked with #Before and #After are run immediately
before and after any test method.
Only static members are shared between test cases. So all instance
members are being reset before any test method.
Also note that as a RULE in Unit Testing, all tests (all test methods) MUST be isolated from each other, but it's OK in integration testing.
I am trying to figure out how to alternatively check if the pointer in the array is currently NULL and loop through. At the moment if the content in that part of the array is deleted it will throw an error when looping.
This array is initialized:
Student *classRosterArray[5] = { nullptr, nullptr, nullptr, nullptr, nullptr };
The loop
void Roster::add(string studentID, string firstName, string lastName, string email, int age, int daysInCourse1, int daysInCourse2, int daysInCourse3, Degree degreeProgram)
{
int courseDaysin[3] = { daysInCourse1, daysInCourse2, daysInCourse3 };
for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
if (classRosterArray[i] == nullptr) {
if (degreeProgram == NETWORKING) {
classRosterArray[i] = new NetworkStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
}
else if (degreeProgram == SECURITY) {
classRosterArray[i] = new SecurityStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
}
else if (degreeProgram == SOFTWARE) {
classRosterArray[i] = new SoftwareStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
}
else {
classRosterArray[i] = new Student(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
}
break;//stop
}
}
}
When Deleted:
void Roster::remove(string studentID)
{
bool studentRemoved = false;
for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
if (classRosterArray[i] != nullptr && classRosterArray[i]->fetchStudentId() == studentID) {
classRosterArray[i] = nullptr;
studentRemoved = true;
break;
}
}
if (studentRemoved == false) {
cout << "ERROR: Student ID '" << studentID << "' was not found.";
}
}
Edited to add following code snippets with the previously suggested modifications how should I go about changing the following now that I am using the Map rather than my original array. Thanks for the help so far guys!
void Roster::printAll()
{
for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
classRosterArray[i]->print();
}
}
void Roster::printByDegreeProgram(int degreeProgram)
{
for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
if (classRosterArray[i]->fetchDegreeProgram() == degreeProgram) {
classRosterArray[i]->print();
}
}
}
void Roster::printDaysInCourse(string studentID)
{
float avg = 0;
int max = 3;
for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
if (classRosterArray[i] != nullptr && classRosterArray[i]->fetchStudentId() == studentID) {
int *daysInCourse = classRosterArray[i]->fetchDaysInCourse();
for (int x = 0; x < max; x++) {
avg += daysInCourse[x];
}
cout << "Student " << classRosterArray[i]->fetchStudentId() << "'s average number of days in each course is." << (avg / max) << "\n";
break;
}
}
}
void Roster::printInvalidEmails()
{
for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
string email = classRosterArray[email]->fetchEmail();
bool isValid = false;
size_t found = email.find("#");
if (found != string::npos) {
found = email.find(".");
if (found != string::npos) {
found = email.find(" ");
if (found == string::npos) {
isValid = true;
}
}
}
if (!isValid) {
cout << email << " is not a valid email address \n";
}
}
}
Problems with your code:
You are using plain C arrays, they are harder to use and easier to break
In your delete method you are not using "delete" to remove the object you have created with "new", so you are leaking every removed student.
If you have more than 5 students your add method fails without any error report
In a real program when you have a huge number of students iterate all of them for every "add" or "remove" operation is a big performance hit.
This is how it should be written in modern C++:
map<string, shared_ptr<Student> > classRosterArray;
void Roster::add(string studentID, string firstName, string lastName, string email, int age, int daysInCourse1, int daysInCourse2, int daysInCourse3, Degree degreeProgram)
{
int courseDaysin[3] = { daysInCourse1, daysInCourse2, daysInCourse3 };
switch (degreeProgram) {
case NETWORKING:
classRosterArray[studentID] = std::shared_ptr<Student>(new NetworkStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram));
break;
case SECURITY:
classRosterArray[studentID] = shared_ptr<Student>(new SecurityStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram));
break;
/* [...] */
default:
classRosterArray[studentID] = shared_ptr<Student>(new Student(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram));
}
}
void Roster::remove(string studentID)
{
auto it = classRosterArray.find(studentID);
if (it != classRosterArray.end())
classRosterArray.erase(it);
else
cout << "ERROR: Student ID '" << studentID << "' was not found.";
}
I'm working on the following C++ application:
Description:
The user enters a number n and the program takes a random collection of cards that are declared at the top of main in the global arrays. It will output a random number of cards each time.
Issue:
The number, e.g. '3 Hearts', appears more than one time. I made a function to correct that, however it didn't solve the issue.
Reference code provided below:
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
string type[4] = {"Hearts" , "Diamonds" , "Spades" , "Clubs"};
string num[13] = {"1","2","3","4","5","6","7","8","9","10","J","Q","K"};
int random(int x)
{
return rand() %x;
}
bool isDrawn(int);
void DrawCard();
int card_remaining = 52;
bool card_is_drawn[52] = {false};
int main()
{
while(1)
{
cout<<"\n Enter A Card Number : ";
int n;
cin>>n;
if(card_remaining <= 0)
{
card_remaining = 52;
cout<<" No More Cards , Refreshing ...\n";
cout<<" Refresh Done ! Try Again if you Want \n";
for(int i=0;i<52;i++)
card_is_drawn[i] = false;
}
else
{
for(int i=0;i<n;i++)
{
DrawCard();
}
}
}
cout<<endl;
system("PAUSE");
return 0;
}
void DrawCard()
{
bool check_1 = false;
int card;
while(!check_1)
{
card = random(card_remaining);
if(!isDrawn(card))
check_1 = true;
}
if(check_1)
cout << num[card%13]<<" OF " << type[card/13] << endl ;
card_remaining--;
}
bool isDrawn(int x)
{
if (card_is_drawn[x] == false)
{
card_is_drawn[x] = true;
return true;
}
return false;
}
Check the function
bool isDrawn(int x){
if(card_is_drawn[x] == false){
card_is_drawn[x] = true;
return true;
}
return false;
}
You might want to exchange the both return values. That means:
if(card_is_drawn[x] == false) {
...
return false; //since the card was NOT drawn;
And at the end of the function:
return true; //since the if-clause evaluated as false what means that the card was drawn;
By the way:
You get your random card by rand()%cards_remaining. That means if you draw ANY card and therefore reduce cards_remaining by one you won't be able to draw the King of Clubs anymore. And going on like this you will loose cards from the 'end' of your deck.
should be:
void DrawCard(){
if (card_remaining <= 0) // no cards left? can't draw
return;
bool check_1 = false;
int card;
while(!check_1){
card = random(52); // here 52
if (isDrawn(card)) // here, if the card HAS been drawn
check_1 = true;
}
if(check_1)
cout << num[card%13]<<" OF " << type[card/13] << endl ;
card_remaining--;
}
I have created an Employee class:
class Employee {
private:
int idNumber;
string name, department, position;
public:
Employee() {
idNumber = 0;
name = department = position = "";
}
Employee(string n, int idn) {
name = n;
idNumber = idn;
department = position = "";
}
Employee(string n, int idn, string dep, string pos) {
name = n;
idNumber = idn;
department = dep;
position = pos;
}
void setName(string n) {
name = n;
}
void setidNumber(int idn) {
idNumber = idn;
}
void setDepartment(string dep) {
department = dep;
}
void setPosition(string pos) {
position = pos;
}
string getName() {
return name;
}
int getidNumber() {
return idNumber;
}
string getDepartment() {
return department;
}
string getPosition() {
return position;
}
};
Now, i created a 2D array of Pointers of type Employee:
int n=2;
Employee **p = new Employee * [n];
for (int i=0; i < n; i++)
p[i] = new Employee;
I stored two records successfully as under:
Name ID Number Department Position
FS 30 CS BS
AT 27 CS BS
I have this code to delete the record of Employees:
string del_name;
int flag = 0;
cin.ignore();
cout << "Enter name: ";
getline(cin, del_name);
for (int i=0; i < n; i++) {
while (del_name == p[i]->getName() && i < n) {
if (del_name == p[i]->getName()) {
delete p[i];
p[i] = NULL;
--k;
++flag;
cout << "Record deleted." << endl;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
cout << "No record found having name " << del_name << "." << endl;
Now, What's the problem:
If a record is found at multiple times. It deletes successfully even if all the records gets deleted.
But if ALL the records are unique and I delete the records one by one and all the records get deleted in this way then the program gets terminated.
Also, is there any other optimized approach to delete records without using VECTORS.
I hope i have clearly explained my problem. I can provide further details if needed.
Thank you for your time
First, usage of std::vector<> or some other container object is the way to go about this. If you can write code that beats (in terms of speed) written by professional library writers, then go ahead.
Second, what is your goal? If it's to simply deallocate entries in that array depending on some criteria, the loop you wrote is overly complex.
bool recordDeleted = false;
for (int i=0; i < n; ++i)
{
if (del_name == p[i]->getName())
{
delete p[i];
p[i] = NULL;
recordDeleted = true;
}
}
if ( !recordDeleted )
{
// record not found
}
MY CODE:
there is an array in the class "table" to hold newly added book (struct);
add just put in one next to one in the array;
search can use ISBN, title or author, which are all variables in book (struct);
print is supposed to cout the info of book
PROBLEM: print can't print string (variable in book are all string)
MAY NOT BE PROBLEM:
insert,add...this kind of function should work well because when I search some book, it shows "book found"
#include<iostream>
#include<string>
using namespace std;
struct book
{
string isbn;
string title;
string author;
string date;
};
class table
{
public:
//member constant
static const size_t CAPACITY = 30;
//constructor
table() {used = 0;}
//modification
bool insert(book entry);
//constant
size_t hash_isbn(string target_isbn);
size_t hash_title(string target_title);
size_t hash_author(string target_author);
size_t search_isbn(string target_isbn);
size_t search_title(string target_title);
size_t search_author(string target_author);
void print(size_t index);
private:
//member variables
book data[CAPACITY];
size_t used;
};
//modification member functions
bool table::insert(book entry)
{
if(search_isbn(entry.isbn))
return false;
data[used] = entry;
used++;
return true;
}
//constant member functions
size_t table::hash_isbn(string target_isbn)
{
size_t index = 0;
bool found = false;
while((index < used) && (!found))
{
if(data[index].isbn == target_isbn)
{
found = true;
continue;
}
index ++;
}
if(!found)
index = -1;
return index;
}
size_t table::hash_title(string target_title)
{
size_t index = 0;
bool found = false;
while((index < used) && !found)
{
if(data[index].title == target_title)
{
found = true;
continue;
}
index ++;
}
if(index == used)
index = -1;
return index;
}
size_t table::hash_author(string target_author)
{
size_t index = 0;
bool found = false;
while((index < used) && !found)
{
if(data[index].author == target_author)
{
found = true;
continue;
}
index ++;
}
if(index == used)
index = -1;
return index;
}
size_t table::search_isbn(string target_isbn)
{
return hash_isbn(target_isbn)+1;
}
size_t table::search_title(string target_title)
{
return hash_isbn(target_title)+1;
}
size_t table::search_author(string target_author)
{
return hash_isbn(target_author)+1;
}
void table::print(size_t index)
{
cout.flush();
cout<<data[index].title<<endl;
cout<<"Title: "<<data[index].title<<endl;
cout<<"ISBN: "<<data[index].isbn<<endl;
cout<<"Author: "<<data[index].author<<endl;
cout<<"Publication data: "<<data[index].date<<endl;
cout<<endl;
}
//nonmember functions
void add(table t)
{
book entry;
cout<<"Enter author name:"<<endl;
cin>>entry.author;
cout<<endl;
cout<<"Enter book name:"<<endl;
cin>>entry.title;
cout<<endl;
cout<<"Enter ISBN:"<<endl;
cin>>entry.isbn;
cout<<endl;
cout<<"Enter the publication data:"<<endl;
cin>>entry.date;
cout<<endl;
if(t.search_isbn(entry.isbn))
cout<<"==== The book already exists !!! ==="<<endl;///////////////////////输入重复时,此处并未执行
else
t.insert(entry);
}
void search(table t)
{
string option;
cout<<"Seach by ISBN (I), book title (T), or author (A). Choice: ";
cin>>option;
cout<<endl;
while((option != "I") && (option != "T") && (option != "A"))
{
cout<<"Not an accessible option, try again:"<<endl
<<"Seach by ISBN (I), book title (T), or author (A). Choice: ";
cin>>option;
cout<<endl;
}
size_t index;
if(option == "I")
{
string target_isbn;
cout<<"Enter ISBN: ";
cin>>target_isbn;
cout<<endl;
index = t.search_isbn(target_isbn);
}
if(option == "T")
{
string target_title;
cout<<"Enter Title: ";
cin>>target_title;
cout<<endl;
index = t.search_isbn(target_title);
}
if(option == "A")
{
string target_author;
cout<<"Enter Author: ";
cin>>target_author;
cout<<endl;
index = t.search_isbn(target_author);
}
if(index+1)
{
cout<<"Book found"<<endl;
t.print(index);
}
else
cout<<"==== The book does not exist !!! ==="<<endl;
}
int main()
{
table hash_table;
string action;
bool done = false;
while(!done)
{
cout<<"Add a new book (A), search (S), or end program (E)? ";
cin>>action;
cout<<endl;
while((action != "A") && (action != "S") && (action != "E"))
{
cout<<"Not an accessible option, try again:"<<endl
<<"Add a new book (A), search (S), or end program (E)? ";
cin>>action;
cout<<endl;
}
if(action == "A")
add(hash_table);
if(action == "S")
search(hash_table);
if(action == "E")
{
done = true;
continue;
}
}
hash_table.print(0); // this code just try to test my problem in a simple way
system("pause");
return 0;
}
The problem is not with print function or something related with it. In function add(and search too) you pass table object by value. Just pass by reference.
void add(table& t)
// ^