In the proccess of creating a user register, I see a double do {} while loop with a same condition. The condition is if detected a space in the strings, the reading will not become available.
void createAccount()
{
unsigned short int i = 0;
bool space = false;
cin.ignore();
cout << "FIRST NAME: ";
getline(cin, fullName[0]);
do {
cout << "MIDDLE NAME: ";
getline(cin, fullName[1]);
for (i = 0; i < fullName[1].size(); i++)
{
if (fullName[i][1] == 32) {
space = true;
break;
}
else {
space = false;
break;
}
}
} while(space);
/*Reset values for the same loop again (I would not like to write 2 times all of this)
i is reseted at loop-for, which helps.*/
space = false;
do {
cout << "MIDDLE NAME: ";
getline(cin, fullName[1]);
for (i = 0; i < fullName[1].size(); i++)
{
if (fullName[i][1] == 32) {
space = true;
break;
}
else {
space = false;
break;
}
}
} while(space);
fullName[3] = fullName[0] + string(" ") + fullName[1] + string(" ") + fullName[2];
}
I really don't know how can I put this together in a same loop. I'm mind broken.
#edit: I'm roger that the right thing is to put fullName[1][i] and that the breaks conditions are wrong.
#edit²: The result:
class BankAccount
{
private:
string fullName[5];
char accountAddress[10];
unsigned short int cards;
float money;
bool visa, mastercard, americanExpress;
void checkName(string name, string typeName, bool exception)
{
unsigned short int errorVar, i;
errorVar = i = 0;
bool space = false;
do {
if (errorVar > 0)
cout << "Enter only the name purposed." << endl << endl;
if (exception)
cout << typeName << " NAME (type no if you haven't): ";
else
cout << typeName << " NAME: ";
getline(cin, name);
for (i = 0; i < name.size(); i++)
{
if (name[i] == ' ')
{
space = true;
break;
}
else
space = false;
}
errorVar++;
} while (space);
if (name.compare("no") == 0)
name = "NULL";
}
public:
void createAccount()
{
cout << endl << "FIRST NAME: "; /* First name has no checks (it can be a compound name) */
getline(cin, this->fullName[0]);
checkName(this->fullName[1], "SECOND", false);
checkName(this->fullName[2], "THIRD", true);
checkName(this->fullName[3], "LAST", false);
if (this->fullName[2].compare("NULL") == 0)
{
this->fullName[4] = this->fullName[0] + string(" ") + this->fullName[1] + string(" ") + this->fullName[3]; //NOT FULL NAME
cout << this->fullName[4];
}
else
{
this->fullName[4] = this->fullName[0] + string(" ") + this->fullName[1] + string(" ") + this->fullName[2] + string(" ") + this->fullName[3]; //NOT FULL NAME
cout << this->fullName[4];
}
}
BankAccount() {/* Constructor */}
~BankAccount() {/* Deconstructor */}
};
Logically it's a simple stuff. Thanks for helping and improve the code also in other areas.
The obvious and clean solution is to put the do-loop in a function (or method), and call it twice, once with fullname[1] and then again with fullname[2].
Related
I'm sorry for the vague title, but I don't know what else to say.
Here is my program:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int
main (int argc, char **argv)
{
//string fin;
string ttl, dscp, ext;
string west = "w";
string east = "e";
string north = "n";
string south = "s";
int numRooms;
//string argv[1] = filename;
class Room
{
public:string title;
string description;
string exits;
int exitWest = -1;
int exitNorth = -1;
int exitEast = -1;
int exitSouth = -1;
int numExits;
};
ifstream fin;
fin.open (argv[1]);
//cin.ignore();
int t = 0;
while (fin)
{
string tilde;
string tester;
tester = "~";
cin >> tilde;
if (tilde == tester)
{
t = t + 1;
}
(numRooms = t / 3);
}
Room *roomArrayPtr = new Room[numRooms];
fin.clear ();
while (fin)
{
for (int l = 0; l < numRooms; l++)
{
getline (fin, ttl, '~');
roomArrayPtr[l].title = ttl;
getline (fin, dscp, '~');
roomArrayPtr[l].description = dscp;
getline (fin, ext, '~');
stringstream sin;
sin << ext;
string x;
int y;
while (sin >> x >> y)
{
if (x == west)
{
roomArrayPtr[l].exitWest = y;
}
if (x == south)
{
roomArrayPtr[l].exitSouth = y;
}
if (x == north)
{
roomArrayPtr[l].exitNorth = y;
}
if (x == east)
{
roomArrayPtr[l].exitEast = y;
}
}
sin.clear ();
int numext;
numext = (ext.size ()) / 3;
roomArrayPtr[l].numExits = numext;
}}
//(read in file again populate roomarrayptr w while loop and getline)
//roomArrayPtr[index].title = line;
//roomArrayPtr[index].description=line;
//close files, while loop that reads in user input from stdin, delete pointers w (delete[] roomArrayPtr;)
//if (exitsarray[i].size() > 2){
char command;
char newcommand;
cout << ">";
cin >> command;
int currentroom = 0;
int newroom;
bool keepgoing = true;
//string dir1;
while (keepgoing)
switch (command)
{
// stringstream ss;
case 'l':
cout << roomArrayPtr[currentroom].title << endl;
cout << roomArrayPtr[currentroom].description << endl;
cout << endl;
//if (roomArrayPtr[currentroom].numExits < 2) {
cout << "Exits: ";
if (roomArrayPtr[currentroom].exitWest > -1)
{
cout << "w";
}
if (roomArrayPtr[currentroom].exitNorth > -1)
{
cout << "n";
}
if (roomArrayPtr[currentroom].exitSouth > -1)
{
cout << "s";
}
if (roomArrayPtr[currentroom].exitEast > -1)
{
cout << "e";
}
/*else {
cout << "Exits: " ;
for (int k = 0; k < numExits; k++){
cout << exitdirection << " ";
}
}*/
//string newcommand;
cin >> newcommand;
//int newroom;
switch (newcommand)
{
case 'w':
if (roomArrayPtr[currentroom].exitWest == -1)
{
cout << "You can't go WEST!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitWest;
cout << "You moved WEST." << endl;
}
break;
case 'e':
if (roomArrayPtr[currentroom].exitEast == -1)
{
cout << "You can't go EAST!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitEast;
cout << "You moved EAST." << endl;
}
break;
case 'n':
if (roomArrayPtr[currentroom].exitNorth == -1)
{
cout << "You can't go NORTH!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitNorth;
cout << "You moved NORTH." << endl;
}
break;
case 's':
if (roomArrayPtr[currentroom].exitSouth == -1)
{
cout << "You can't go SOUTH!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitSouth;
cout << "You moved SOUTH." << endl;
}
break;
}
break;
case 'q':
keepgoing = false;
return 0;
break;
currentroom = newroom;
}
}
Whenever I run it, it compiles, but nothing happens. I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up. What's going on?
I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up.
you are reading the wrong file
int t = 0;
while (fin)
{
string tilde;
string tester;
tester = "~";
cin >> tilde; <<<<===== i assume you mean fin
if (tilde == tester)
{
t = t + 1;
}
(numRooms = t / 3);
}
#include <cstring>
#include <string>
#include <cstdlib>
#include <ctype.h>
using namespace std;
const int MAX = 100;
class SampleEx{
public:
SampleEx(int, char);
void setNum(int);
int getNum();
void setCh(char);
char getCh();
private:
int number;
char c;
};
SampleEx :: SampleEx (int n, char c)
{
this->number =n;
this->c = c;
}
void SampleEx::setNum(int n){number = n;}
int SampleEx::getNum(){return number;}
void SampleEx::setCh(char n){c = n;}
char SampleEx::getCh(){return c;}
char Read (char[]);
void analyze(char[], int char_loc, int & size);
void DigitProcess(char[], int char_loc, int & size);
void AlphaProcess(char[], int char_loc, int & size);
void printStatus(int status);
int nextSpace(char[], int char_loc, int & size);
int main() {
int status = 0, char_loc = 0, size = 0;
char cont = ' ';
char lexeme[MAX];
char next = ' ';
do
{
try
{
do
{
next = Read(lexeme);
cout << lexeme;
analyze(lexeme, char_loc, size);
} while (next !='\n');
}
catch (SampleEx &e)
{
// cout << "Exception Number: " << e.getNum() << " Char: " << e.getCh() << '\n';
switch(e.getNum())
{
case 1:
cout << "[Invalid Integer: " << e.getCh() << " Found.] ";
break;
case 2:
cout << "[Invalid Decimal: " << e.getCh() << " Found.] ";
break;
case 3:
cout << "[Invalid Decimal: " << "Too Many . Found.] ";
break;
case 4:
cout << "[Invalid ID: " << e.getCh() << " Found.] ";
break;
}
}
cout << endl << "Continue? Y] Yes N] No" << endl;
cin.ignore(size);
cin >> cont;
while (cont != 'Y' && cont != 'N')
{
cout << "Invalid Input. Try Again." << endl;
cin >> cont;
}
if (cont == 'Y')
{
cin.ignore();
}
} while(cont != 'N');
cout << "Program Ended." << endl;
return 0;
}
void analyze(char item[], int char_loc, int & size)
{
SampleEx s1(0, ' ');
if (isdigit(item[0]))
{
DigitProcess(item, char_loc, size);
}
else if (isalpha(item[0]))
{
AlphaProcess(item, char_loc, size);
}
else if (item[0] == '.')
{
s1.setCh(item[0]);
s1.setNum(2);
throw s1;
}
else
{
s1.setCh(item[0]);
s1.setNum(4);
throw s1;
}
}
char Read(char temp[])
{
char extra;
int size = 0;
cin.get(extra);
while (size < MAX && extra != ' ' && extra != '\n')
{
temp[size] = extra;
cin.get(extra);
size++;
}
temp[size] = '\0';
return extra;
}
void DigitProcess(char item[], int char_loc, int & size)
{
SampleEx error(0, ' ');
size = strlen(item);
bool decimalMax = false, alphaUsed = false;
for (char_loc = 1; char_loc < size; char_loc++)
{
if (isdigit(item[char_loc]))
{
continue;
}
else if (isalpha(item[char_loc]))
{
error.setCh(item[char_loc]);
error.setNum(1);
throw error;
alphaUsed = true;
break;
}
else if (item[char_loc] == '.')
{
if (decimalMax == true)
{
error.setCh(item[char_loc]);
error.setNum(3);
throw error;
}
decimalMax = true; // stops anymore decimals from being entered
}
else
{
error.setCh(item[char_loc]);
error.setNum(4);
throw error;
}
}
if (decimalMax == true && alphaUsed == false)
{
printStatus(1);
}
else if (decimalMax == false && alphaUsed == false)
{
printStatus(2);
}
}
void AlphaProcess(char item[], int char_loc, int & size)
{
SampleEx error(0, ' ');
size = strlen(item);
bool digitUsed = false, deciUsed = false;
for (char_loc = 1; char_loc < size; char_loc++)
{
if (isalpha(item[char_loc]))
{
continue;
}
else if (isdigit(item[char_loc]))
{
digitUsed = true;
error.setCh(item[char_loc]);
error.setNum(4);
throw error;
for (int i = char_loc; i < size; i++)
{
if (isspace(item[i]))
{
char_loc = i - 1;
break;
}
}
}
else if (item[char_loc] == '.')
{
deciUsed = true;
error.setCh(item[char_loc]);
error.setNum(4);
throw error;
break;
}
else
{
error.setCh(item[char_loc]);
error.setNum(4);
throw error;
}
}
if (digitUsed == false && deciUsed == false)
{
printStatus(3);
}
}
void printStatus(int status)
{
switch(status)
{
case 1:
cout << "Decimal ";
break;
case 2:
cout << "Integer ";
break;
case 3:
cout << "ID ";
}
}
The above code will give "ID" if I were to say something like x or mike, "Decimal" if I were to say something like 4.4424, "Integer" if I were to say like 444.
However, it will print an error if anything is invalid, like if I put .333, it should print an error. The issue is that the program refuses to print multiple errors at a time.
For example: if I were to put "taco taco taco", it should print ID ID ID.
but if I were to put taco taco taco1, it would print ID ID [Invalid ID: 1 found]
The problem is that if I were to put taco taco1 taco1, it would NOT print the following:
ID [Invalid ID: 1 found] [Invalid ID: 1 found]
which that is the goal.
I'm trying to limit user input to certain characters only [a-z,A-Z,SPACE,PERIOD], I can't get this function right?!
void setName()
{
char fname[20];
unsigned int ascii_val;
while(ascii_val<65 || ascii_val>90)
{
cout << "First Name: ";
cin.ignore().getline(fname,20);
for(int i=0; i<sizeof(fname); i++)
{
ascii_val = toupper(fname[i]);
if(ascii_val==32 || ascii_val==46 || ascii_val==0) //Exception to allow SPACE and PERIOD
{
ascii_val=65;
};
if(ascii_val<65 || ascii_val>90)
{
cout << "Only Alphabet [a-z,A-Z,SPACE,DOT] Allowed!\n";
break;
}
}
}
newfname = fname;
}
This finally worked! if you think this is not the best solution, post your alternative please.
bool charVerify(string word)
{
for (int i = 0; i < word.size(); i++)
{
int character = toupper(word[i]);
if(character == ' ' || character == '.')
{
character='A';
}
if (character < 'A' || character > 'Z')
{
return false;
}
}
return true;
}
void setFname()
{
string fname;
cout << "Enter Name: ";
getline(std::cin.ignore(),fname);
while(1)
{
if (charVerify(fname))
{
break;
}
else
{
cout << "\tInvalid Input! Only [a-z,A-Z,SPACE,PERIOD]" << endl;
}
cin.clear();
cout << "Enter Name: ";
getline(std::cin.ignore(),fname);
}
firstname = fname;
}
I'm unsure why when more than one transaction has been made the FOR LOOP won't iterate through the vector of "buyers". Am I missing something simple? I've spent the last few hours trying to fix this but to no avail. If any one could possibly help with my problem I'd be eternally grateful.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
//This class is for the car details that the user can purchase.
class cCar {
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d)
{
_sName = s;
_dPrice = d;
}
string getName() { return _sName; }
double getPrice() { return _dPrice; }
};
//This is where all the car detail purchases are created and stored in the object 'carlist'
vector<cCar> CarDatabase(vector<cCar>& car_list)
{
car_list.push_back(cCar("Blue Nissan Skyline", 1000));
car_list.push_back(cCar("Red Mini", 3000));
car_list.push_back(cCar("Black Land Rover", 4000));
car_list.push_back(cCar("Beatle", 9000));
car_list.push_back(cCar("Ferrari", 300000));
return car_list;
}
//This class stores the user's transactions
class Finance {
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay)
{
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName() { return _sUserName; }
double getdCostOfCar() { return _dCostOfCar; }
string getChosenCar() { return _sChosenCar; }
int getFinancePlan() { return _iFinancePlan; }
double getDepositAmount() { return _dDepositedAmount; }
double getMonthlyAmount() { return _dMonthlyPayments; }
double getTotalLeftToPay() { return _dTotalLeftToPay; }
};
//1. This displays the car menu items.
void display_menu(vector<cCar>& car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++) {
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do {
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if (iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size()) {
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else {
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
} while (iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int& iFinanceLength)
{
do {
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4) {
cout << "\nOops, try again! Please enter between 1 - 4!";
}
} while (iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double& dDepositAmount)
{
do {
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500) {
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
} while (dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char& cOption, bool& bExit)
{
do {
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch (cOption) {
case 'Y':
bExit = false;
break;
case 'N':
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
} while (cOption != 'y' && cOption != 'Y' && cOption != 'n' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1) ? "years" : "year";
}
//This displays receipt of the user's transaction.
//HERE IS WHRERE I "M STRUGGLING TO ITERATE
void Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName, dCostOfChosenCar, sNameOfChosenCar, iFinanceLength, dDepositAmount, dMonthlyPayments, dTotalLeftToPay));
for (int iCount = 0; iCount != buyers.size(); iCount++) {
cout << "\nReceipt for: " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay();
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount();
cout << "\n";
}
RestartOptions(cOption, bExit);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance> buyers)
{
char cOption = 0;
do {
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y' || cOption == 'N') {
if (cOption == 'Y') {
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else {
RestartOptions(cOption, bExit);
}
}
else {
cout << "\nSorry, that's not a valid command.";
}
} while (cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar> car_list;
CarDatabase(car_list);
vector<cCar> car_purchases;
vector<Finance> buyers;
do {
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength, dDepositAmount, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
} while (bExit == false);
}
malloc: *** error for object 0x10ee008c0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
Or I get this when I try and print everything
Segmentation fault: 11
I'm doing some homework for an OOP class and I've been stuck for a good hour now. I'm getting this error once I've used keyboard input enough. I am not someone who gets frustrated at all, and here I am getting very frustrated with this. Here are the files:
This is the book class. I'm pretty sure this is very solid. But just for reference:
//--------------- BOOK.CPP ---------------
// The class definition for Book.
//
#include <iostream>
#include "book.h"
using namespace std;
Book::Book()
//
{
strcpy(title, " ");
strcpy(author, " ");
type = FICTION;
price = 0;
}
void Book::Set(const char* t, const char* a, Genre g, double p)
{
strcpy(title, t);
strcpy(author, a);
type = g;
price = p;
}
const char* Book::GetTitle() const
{
return title;
}
const char* Book::GetAuthor() const
{
return author;
}
double Book::GetPrice() const
{
return price;
}
Genre Book::GetGenre() const
{
return type;
}
void Book::Display() const
{
int i;
cout << GetTitle();
for (i = strlen(title) + 1; i < 32; i++)
cout << (' ');
cout << GetAuthor();
for (i = strlen(author) + 1; i < 22; i++)
cout << (' ');
switch (GetGenre())
{
case FICTION:
cout << "Fiction ";
break;
case MYSTERY:
cout << "Mystery ";
break;
case SCIFI:
cout << "SciFi ";
break;
case COMPUTER:
cout << "Computer ";
break;
}
cout << "$";
if (GetPrice() < 1000)
cout << " ";
if (GetPrice() < 100)
cout << " ";
if (GetPrice() < 10)
cout << " ";
/* printf("%.2f", GetPrice());*/
cout << '\n';
}
This is the store class that deals with the array and dynamic allocation. This was working well without input commands, but just using its functions it was working like a champ.
//--------------- STORE.CPP ---------------
// The class definition for Store.
//
#include <iostream>
#include <cstring> // for strcmp
#include "store.h"
using namespace std;
Store::Store()
{
maxSize = 5;
currentSize = 0;
bookList = new Book[maxSize];
}
Store::~Store()
// This destructor function for class Store
// deallocates the Store's list of Books
{
delete [] bookList;
}
void Store::Insert(const char* t, const char* a, Genre g, double p)
// Insert a new entry into the direrctory.
{
if (currentSize == maxSize)// If the directory is full, grow it.
Grow();
bookList[currentSize++].Set(t, a, g, p);
}
void Store::Sell(const char* t)
// Sell a book from the store.
{
char name[31];
strcpy(name, t);
int thisEntry = FindBook(name);// Locate the name in the directory.
if (thisEntry == -1)
cout << *name << " not found in directory";
else
{
cashRegister = cashRegister + bookList[thisEntry].GetPrice();
// Shift each succeding element "down" one position in the
// Entry array, thereby deleting the desired entry.
for (int j = thisEntry + 1; j < currentSize; j++)
bookList[j - 1] = bookList[j];
currentSize--;// Decrement the current number of entries.
cout << "Entry removed.\n";
if (currentSize < maxSize - 5)// If the directory is too big, shrink it.
Shrink();
}
}
void Store::Find(const char* x) const
// Display the Store's matches for a title or author.
{
// Prompt the user for a name to be looked up
char name[31];
strcpy(name, x);
int thisBook = FindBook(name);
if (thisBook != -1)
bookList[thisBook].Display();
int thisAuthor = FindAuthor(name, true);
if ((thisBook == -1) && (thisAuthor == -1))
cout << name << " not found in current directory\n";
}
void Store::DisplayGenre(const Genre g) const
{
double genrePrice = 0;
int genreCount = 0;
for (int i = 0; i < currentSize; i++)// Look at each entry.
{
if (bookList[i].GetGenre() == g)
{
bookList[i].Display();
genrePrice = genrePrice + bookList[i].GetPrice();
genreCount++;
}
}
cout << "Number of books in this genre: " << genreCount
<< " " << "Total: $";
if (genrePrice < 1000)
cout << " ";
if (genrePrice < 100)
cout << " ";
if (genrePrice < 10)
cout << " ";
printf("%.2f", genrePrice);
}
void Store::DisplayStore() const
{
if (currentSize >= 1)
{
cout << "**Title**\t\t"
<< "**Author**\t"
<< "**Genre**\t"
<< "**Price**\n\n";
for (int i = 0; i < currentSize; i++)
bookList[i].Display();
}
else
cout << "No books currently in inventory\n\n";
cout << "Total Books = " << currentSize
<< "\nMoney in the register = $";
if (cashRegister < 1000)
cout << " ";
if (cashRegister < 100)
cout << " ";
if (cashRegister < 10)
cout << " ";
printf("%.2f", cashRegister);
cout << '\n';
}
void Store::Sort(char type)
{
Book temp;
for(int i = 0; i <= currentSize; i++)
{
for (int j = i+1; j < currentSize; j++)
{
if (type == 'A')
{
if (strcmp(bookList[i].GetTitle(), bookList[j].GetTitle()) > 0)
{
temp = bookList[i];
bookList[i] = bookList[j];
bookList[j] = temp;
}
}
if (type == 'T')
{
if (strcmp(bookList[i].GetAuthor(), bookList[j].GetAuthor()) > 0)
{
temp = bookList[i];
bookList[i] = bookList[j];
bookList[j] = temp;
}
}
}
}
}
void Store::SetCashRegister(double x)
// Set value of cash register
{
cashRegister = x;
}
void Store::Grow()
// Double the size of the Store's bookList
// by creating a new, larger array of books
// and changing the store's pointer to refer to
// this new array.
{
maxSize = currentSize + 5;// Determine a new size.
cout << "** Array being resized to " << maxSize
<< " allocated slots" << '\n';
Book* newList = new Book[maxSize];// Allocate a new array.
for (int i = 0; i < currentSize; i++)// Copy each entry into
newList[i] = bookList[i];// the new array.
delete [] bookList;// Remove the old array
bookList = newList;// Point old name to new array.
}
void Store::Shrink()
// Divide the size of the Store's bookList in
// half by creating a new, smaller array of books
// and changing the store's pointer to refer to
// this new array.
{
maxSize = maxSize - 5;// Determine a new size.
cout << "** Array being resized to " << maxSize
<< " allocated slots" << '\n';
Book* newList = new Book[maxSize];// Allocate a new array.
for (int i = 0; i < currentSize; i++)// Copy each entry into
newList[i] = bookList[i];// the new array.
delete [] bookList;// Remove the old array
bookList = newList;// Point old name to new array.
}
int Store::FindBook(char* name) const
// Locate a name in the directory. Returns the
// position of the entry list as an integer if found.
// and returns -1 if the entry is not found in the directory.
{
for (int i = 0; i < currentSize; i++)// Look at each entry.
if (strcmp(bookList[i].GetTitle(), name) == 0)
return i;// If found, return position and exit.
return -1;// Return -1 if never found.
}
int Store::FindAuthor(char* name, const bool print) const
// Locate a name in the directory. Returns the
// position of the entry list as an integer if found.
// and returns -1 if the entry is not found in the directory.
{
int returnValue;
for (int i = 0; i < currentSize; i++)// Look at each entry.
if (strcmp(bookList[i].GetAuthor(), name) == 0)
{
if (print == true)
bookList[i].Display();
returnValue = i;// If found, return position and exit.
}
else
returnValue = -1;// Return -1 if never found.
return returnValue;
}
Now this is the guy who needs some work. There may be some stuff blank so ignore that. This one controls all the input, which is the problem I believe.
#include <iostream>
#include "store.h"
using namespace std;
void ShowMenu()
// Display the main program menu.
{
cout << "\n\t\t*** BOOKSTORE MENU ***";
cout << "\n\tA \tAdd a Book to Inventory";
cout << "\n\tF \tFind a book from Inventory";
cout << "\n\tS \tSell a book";
cout << "\n\tD \tDisplay the inventory list";
cout << "\n\tG \tGenre summary";
cout << "\n\tO \tSort inventory list";
cout << "\n\tM \tShow this Menu";
cout << "\n\tX \teXit Program";
}
char GetAChar(const char* promptString)
// Prompt the user and get a single character,
// discarding the Return character.
// Used in GetCommand.
{
char response;// the char to be returned
cout << promptString;// Prompt the user
cin >> response;// Get a char,
response = toupper(response);// and convert it to uppercase
cin.get();// Discard newline char from input.
return response;
}
char Legal(char c)
// Determine if a particular character, c, corresponds
// to a legal menu command. Returns 1 if legal, 0 if not.
// Used in GetCommand.
{
return((c == 'A') || (c == 'F') || (c == 'S') ||
(c == 'D') || (c == 'G') || (c == 'O') ||
(c == 'M') || (c == 'X'));
}
char GetCommand()
// Prompts the user for a menu command until a legal
// command character is entered. Return the command character.
// Calls GetAChar, Legal, ShowMenu.
{
char cmd = GetAChar("\n\n>");// Get a command character.
while (!Legal(cmd))// As long as it's not a legal command,
{// display menu and try again.
cout << "\nIllegal command, please try again . . .";
ShowMenu();
cmd = GetAChar("\n\n>");
}
return cmd;
}
void Add(Store s)
{
char aTitle[31];
char aAuthor[21];
Genre aGenre = FICTION;
double aPrice = 10.00;
cout << "Enter title: ";
cin.getline(aTitle, 30);
cout << "Enter author: ";
cin.getline(aAuthor, 20);
/*
cout << aTitle << " " << aAuthor << "\n";
cout << aGenre << " " << aPrice << '\n';
*/
s.Insert(aTitle, aAuthor, aGenre, aPrice);
}
void Find()
{
}
void Sell()
{
}
void ViewGenre(Store s)
{
char c;
Genre result;
do
c = GetAChar("Enter Genre - (F)iction, (M)ystery, (S)ci-Fi, or (C)omputer: ");
while ((c != 'F') && (c != 'M') && (c != 'S') && (c != 'C'));
switch (result)
{
case 'F': s.DisplayGenre(FICTION); break;
case 'M': s.DisplayGenre(MYSTERY); break;
case 'S': s.DisplayGenre(SCIFI); break;
case 'C': s.DisplayGenre(COMPUTER); break;
}
}
void Sort(Store s)
{
char c;
Genre result;
do
c = GetAChar("Enter Genre - (F)iction, (M)ystery, (S)ci-Fi, or (C)omputer: ");
while ((c != 'A') && (c != 'T'));
s.Sort(c);
}
void Intro(Store s)
{
double amount;
cout << "*** Welcome to Bookstore Inventory Manager ***\n"
<< "Please input the starting money in the cash register: ";
/* cin >> amount;
s.SetCashRegister(amount);*/
}
int main()
{
Store mainStore;// Create and initialize a Store.
Intro(mainStore);//Display intro & set Cash Regsiter
ShowMenu();// Display the menu.
/*mainStore.Insert("A Clockwork Orange", "Anthony Burgess", SCIFI, 30.25);
mainStore.Insert("X-Factor", "Anthony Burgess", SCIFI, 30.25);*/
char command;// menu command entered by user
do
{
command = GetCommand();// Retrieve a command.
switch (command)
{
case 'A': Add(mainStore); break;
case 'F': Find(); break;
case 'S': Sell(); break;
case 'D': mainStore.DisplayStore(); break;
case 'G': ViewGenre(mainStore); break;
case 'O': Sort(mainStore); break;
case 'M': ShowMenu(); break;
case 'X': break;
}
} while ((command != 'X'));
return 0;
}
Please, any and all help you can offer is amazing.
Thank you.
Welcome to the exciting world of C++!
Short answer: you're passing Store as a value. All your menu functions should take a Store& or Store* instead.
When you're passing Store as a value then an implicit copy is done (so the mainStore variable is never actually modified). When you return from the function the Store::~Store is called to clean up the copied data. This frees mainStore.bookList without changing the actual pointer value.
Further menu manipulation will corrupt memory and do many double frees.
HINT: If you're on linux you can run your program under valgrind and it will point out most simple memory errors.
Your Store contains dynamically-allocated data, but does not have an assignment operator. You have violated the Rule of Three.
I don't see the Store class being instantiated anywhere by a call to new Store() which means the booklist array has not been created but when the program exits and calls the destructor, it tries to remove the array that was never allocated and hence that's why i think you are getting this error. Either, modify the destructor to have a null check or instantiate the class by a call to the constructor. Your code shouldn't still be working anywhere you are trying to use a Store object.
Hope this helps