Right now I have a working scrolling menu, I just wanted to ask if there is anyone to give tips how to compact this because it's a bit "CHUNKY"!
Also I have two extra questions: How can I change it for my
"Rock,
Paper,
Scissors"
to be displayed like "Rock, Paper", Scissors"? If you try out my code, you'd see the text is all vertical, can I make it all horizontal? And is there any tips how to make it into a void statement to be used multiple times?
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
string Menu[3] = {"Rock", "Paper", "Scissors"};
int pointer = 0;
while(true)
{
system("cls");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "Main Menu\n\n";
for (int i = 0; i < 3; ++i)
{
if (i == pointer)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
cout << Menu[i] << endl;
}
else
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << Menu[i] << endl;
}
}
while(true)
{
if (GetAsyncKeyState(VK_UP) != 0)
{
pointer -= 1;
if (pointer == -1)
{
pointer = 2;
}
break;
}
else if (GetAsyncKeyState(VK_DOWN) != 0)
{
pointer += 1;
if (pointer == 3)
{
pointer = 0;
}
break;
}
else if (GetAsyncKeyState(VK_RETURN) != 0)
{
switch (pointer)
{
case 0:
{
cout << "\n\n\nStarting new game...";
Sleep(1000);
} break;
case 1:
{
cout << "\n\n\nThis is the options...";
Sleep(1000);
} break;
case 2:
{
return 0;
} break;
}
break;
}
}
Sleep(150);
}
return 0;
}
There's a bunch of different ways you could go about this. I'd prefer to go about it a different way in my own code,but have tried to write something that was as close to your own code as I could at this hour of the day.
You can re-use the same function for any menu that needs displaying - just give it a different value for the list of strings and the count of the number of strings in that array. Even better - use a std::vector<string>.
Rather than hard-code the number of menu items in the main function, I work it out by taking the total size of the array of strings and dividing it by the size of the first element. Since each element gives the same value for sizeof regardless of the length of the string, this allows you to calculate the number of elements in the array. Note though - this trick won't work inside of the getUserChoice function though - by that time, the array had been degraded to a pointer and the function has no way of telling how many items are in the array, unlike main - that's why I calculate the number there. Using a vector of strings would be much cleaner, since you could just pass a reference to the vector to the function, then inside the function you could call the .size() method of the vector to get the number of items it contains. Probably a little in front of where you're up to just now, hence the code in a similar style to your own.
Hope its helpful. :)
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int getUserChoice(string *items, int numItems)
{
int curSel = 0, textAttrib;
bool selectionMade = false, needsUpdate = true; // we want to clearscreen first time through
while (!selectionMade)
{
// only redraw the screen if something has changed, or we're on the first iteration of
// our while loop.
if (needsUpdate)
{
system("cls");
needsUpdate = false;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "Main Menu" << endl;
cout << "(navigate with arrow keys, select with enter)" << endl << endl;
for (int i=0; i<numItems; i++)
{
if (i == curSel)
textAttrib = 11;
else
textAttrib = 15;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), textAttrib);
if (i)
cout << " ";
cout << items[i];
}
}
if (GetAsyncKeyState(VK_LEFT) != 0)
{
curSel--;
needsUpdate = true;
}
else if (GetAsyncKeyState(VK_RIGHT) != 0)
{
curSel++;
needsUpdate = true;
}
else if (GetAsyncKeyState(VK_RETURN) != 0)
selectionMade = true;
if (curSel < 0)
curSel = numItems-1;
else if (curSel > (numItems-1) )
curSel = 0;
Sleep(100);
}
char dummy[10];
cin.getline(dummy, 10); // clear the enter key from the kbd buffer
return curSel;
}
int main()
{
string Menu[] = {"Rock", "Paper", "Scissors"};
int selection;
selection = getUserChoice(Menu, sizeof(Menu)/sizeof(Menu[0]) );
cout << "You chose: " << Menu[selection] << endl;
}
Related
I am working on a project and I want to make a Graphics Menu. Issue which I am facing is that after it shows any text written in the function I've put in switch. it goes back to main menu. I want to make a function which stays on new function and once it directs to new function, It has nothing to do with main menu anymore. Until this function is called again.
I want it to be a simple menu function which directs me to function. Nothing else.
your help would mean allot!
Thanks in advance.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<iomanip>
#include<fstream>
#include<windows.h>
using namespace std;
int main() {
system("cls");
string Menu[3] = { " Admin", " Customer", " Exit" };
int pointer = 0;
bool flag=true;
while (flag==true)
{
system("cls");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "Main Menu\n\n";
for (int i = 0; i < 3; ++i)
{
if (i == pointer)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
cout << Menu[i] << endl;
}
else
{
SetConsoleTextAttribute ( GetStdHandle ( STD_OUTPUT_HANDLE), 15);
cout << Menu[i] << endl;
}
}
while (true)
{
if (GetAsyncKeyState(VK_UP) != 0)
{
pointer =pointer-1;
if (pointer == -1)
{
pointer = 2;
}
break;
}
else if (GetAsyncKeyState(VK_DOWN) != 0)
{
pointer += 1;
if (pointer == 3)
{
pointer = 0;
}
break;
}
else if (GetAsyncKeyState(VK_RETURN) != 0)
{
switch (pointer)
{
case 0:
{
admin_login();
Sleep(500);
break;
}
case 1:
{
customer_sign();
Sleep(500);
break;
}
case 2:
{
thank_you();
Sleep(800);
break;
}
default:
{
cout<<"Invalid Input! ";
}
}
}
}
Sleep(150);
}
return 0;
}
Your 'flag' boolean needs to be checked as the condition for both while loops, not just the first one. You also need to clear the console when you press enter on a menu selection.
Inside your switch case after detecting key press, in each case you need to set your flag boolean to false so you stop drawing the main menu, and instead start drawing the sub menus. I don't have access to your other functions so here is a solution emulating that behaviour in a simplified and minimal reproducible proof of concept:
#include<windows.h>
#include <iostream>
using namespace std;
int main()
{
system("cls");
string Menu[3] = { " Admin", " Customer", " Exit" };
int pointer = 0;
bool bMainMenu = true;
while (bMainMenu)
{
system("cls");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "Main Menu\n\n";
for (int i = 0; i < 3; ++i)
{
if (i == pointer)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
cout << Menu[i] << endl;
}
else
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << Menu[i] << endl;
}
}
while (bMainMenu)
{
if (GetAsyncKeyState(VK_UP)&1)
{
pointer = pointer - 1;
if (pointer == -1)
{
pointer = 2;
}
break;
}
else if (GetAsyncKeyState(VK_DOWN)&1)
{
pointer += 1;
if (pointer == 3)
{
pointer = 0;
}
break;
}
else if (GetAsyncKeyState(VK_RETURN)&1)
{
switch (pointer)
{
case 0:
{
//admin_login();
system("cls");
std::cout << "admin selected\n";
Sleep(1000);
bMainMenu = false;
break;
}
case 1:
{
//customer_sign();
system("cls");
std::cout << "customer selected\n";
Sleep(1000);
bMainMenu = false;
break;
}
case 2:
{
//thank_you();
system("cls");
std::cout << "thank you selected\n";
Sleep(1000);
bMainMenu = false;
break;
}
default:
{
cout << "Invalid Input! ";
}
}
}
}
Sleep(150);
}
return 0;
}
So I'm still fairly new to c++ and programming in general, but I'd like to assume that I have a fairly good grasp of the concept and control flow (possibly lol). I'm currently creating a top down style game that allows the user to interact with the inventory of a chest. The problem that has me extremely confused is that I modify a variable but then it changes to something entirely different after "updating" the console.
Interactive chest inventory displaying 10 gold
After pressing s to update the console
The gold amount in the chest is set to 10 in the chestLoot() function, but is then changed to a value of 303, which is the macro for the Healing potion. Why is the chest.gold value being changed to 303 after I set it to 10? Any help on this would be much appreciated. (Don't be too harsh, I'm still new to stack overflow and c++ as well as programming in general)
Here is the code that handles the chest inventory as well as the loot that is generated:
void chestLoot(int x)
{
switch (tutorial.chestIt)
{
case 0:
chest.inventory[x] = WOODEN_SWORD_ID;
break;
case 1:
chest.inventory[x] = GOLD_ID;
chest.gold = 10;
break;
case 2:
chest.inventory[x] = HEALING_POTION_ID;
break;
case 3:
chest.inventory[x] = LEATHER_HELMET_ID;
break;
}
tutorial.chestIt++;
}
void chestInventory()
{
bool endLoop = false;
int x = 0;
int selection = 0;
int highlighted = 0;
while (endLoop == false)
{
system("cls");
std::cout << "Chest:" << std::endl << std::endl;
if (tutorial.gridChestOpened == false)
updatePlayer(5);
for (x = 0; x <= player.level + 3; x++)
{
if (tutorial.gridChestOpened == false)
{
chestLoot(x);
}
switch (chest.inventory[x])
{
case WOODEN_SWORD_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << "Wooden Sword";
break;
case GOLD_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << chest.gold << " Gold";
break;
case HEALING_POTION_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << "Healing Potion";
break;
case LEATHER_HELMET_ID:
std::cout << x + 1 << ". ";
if (selection == x)
{
std::cout << "- ";
highlighted = selection;
}
std::cout << "Leather Helmet";
break;
case NULL:
break;
}
std::cout << std::endl;
}
tutorial.gridChestOpened = true;
switch (_getch())
{
case 'w':
--selection;
if (selection < 0)
selection = 0;
if (chest.inventory[selection] == NULL)
++selection;
break;
case 's':
++selection;
if (selection > tutorial.chestIt)
selection = tutorial.chestIt;
if (chest.inventory[selection] == NULL)
--selection;
break;
case 'e':
if (chest.inventory[highlighted] == 0)
{
std::cout << "There is nothing there";
break;
}
else if (chest.inventory[highlighted] == GOLD_ID)
{
player.gold = player.gold + chest.gold;
chest.inventory[highlighted] = NULL;
break;
}
else
{
for (int y = 1; y <= player.level + 9; y++)
{
if (player.inventory[y] == NULL)
{
player.inventory[y] = chest.inventory[highlighted];
chest.inventory[highlighted] = NULL;
}
}
}
break;
case 27:
endLoop = true;
drawScreen(NULL);
break;
}
}
}
Here are the global variables that are used in the function:
struct Loot
{
int inventory[2];
int gold;
}chest, pot;
struct Entity
{
int position[2] = { 2, 2 };
int gold = 0;
int health = 10;
int level = 1;
int totalXp = 0;
int inventory[11];
int mainHand[2] = {/*location, item*/};
}player/*enemy*/;
struct Grid
{
int grid[6][12] = {
{1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1},
{1,0,0,0,0,2,0,1,0,0,3,1},
{1,0,2,0,0,0,0,1,0,0,0,1},
{1,0,0,0,0,2,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,4,1}
};
bool gridChestOpened = false;
int chestIt = 0;
}tutorial;
// Item ID's
#define WOODEN_SWORD_ID 301
#define GOLD_ID 302
#define HEALING_POTION_ID 303
#define LEATHER_HELMET_ID 304
Any tips on improving my code are much appreciated as well :)
2: Check HerePassing a variable from one function to another
Your problem is that the member inventory of Loot is not dimensioned properly. The only valid values for x in chest.invetory[x] are 0 and 1. Your code is however clearly writing to chest.inventory[2], for example when you call chestLoot(2).
The memory in a struct is laid out sequentially, so chest.inventory[2] = HEALING_POTION_ID; will quietly overwrite the next 4 bytes after the chest.inventory[1] which is chest.gold;
Well, the inventory member of your "loot" struct is an array of ints of length 2. But you seem to be calling "chestLoot" with a value greater than 1. This is causing you to go off the end of your array and write to where "gold" should be.
So I was to create a program that would verify a password is created correctly. To pass verification, the user must enter 6 or more characters, have at least one lower case letter, one upper case letter, and one digit. The catch is I had to use only the cstring (and of course cctype) library and not the string library. The program runs fine if the user creates an incorrect password, if they successfully create a good password then it sometimes (not sure why sometimes) it crashes. An answer to this, will help me solidify my understanding more on pointers an allocation of memory in terms of it being dynamic. With that here is the program in question.
#include <iostream>
#include <cctype>
#include <cstring>
bool isVerifyAccepted(char*, int);
using namespace std;
int main() {
const int SIZE = 6;
char *userPass = new char[SIZE];
cout << "Verify you have a good password\na good password has to be at least six characters long\n"
<< "have at least on uppercase and one lowercase letter and at least one digit" <<endl <<endl;
cout << "enter a password below" <<endl <<endl;
cin >> userPass;
int userSizePass = strlen(userPass);
char testPassWord[userSizePass];
int count = 0;
while (count < userPass[count]) {
testPassWord[count] = userPass[count];
count++;
}
isVerifyAccepted(testPassWord, userSizePass);
delete[] userPass;
userPass = NULL;
//system("pause");
return 0;
}
bool isVerifyAccepted(char *pass, int size){
bool verify[3];
if(size <= 6){
cout << "Password is too short "<<endl;
return false;
}
for(int i = 0; i<size; i++){
if(islower(pass[i])){
verify[0] = true;
break;
}else{
verify[0] = false;
}
}
for(int i = 0; i<size; i++){
if(isupper(pass[i])){
verify[1] = true;
break;
}else{
verify[1] = false;
}
}
for(int i = 0; i<size; i++){
if(isdigit(pass[i])){
verify[2] = true;
break;
}else{
verify[2] = false;
}
}
if(verify[0] == false){
cout << "You need at least one lowercase letter" << endl;
}
if(verify[1] == false){
cout << "You need at least one uppercase letter" << endl;
}
if(verify[2] == false){
cout << "You need at least one digit" << endl;
}
if((verify[0] == true) && (verify[1] == true) && (verify[2] == true)){
cout << "You have a good password, you met the criteria " <<endl;
}
return verify;
}
Because of this line according to the debugger : const int SIZE = 6.
Increase the size to 32 or some number larger than 6.
Some passwords are longer than 6 characters.
I have the following code below:
int main ()
{
char string[80];
bool Restart;
Restart = true;
while (Restart)
{
cout << "Enter a string\n" << endl;
cin.getline(string, 80);
cout << "\nYou entered: ";
printf(string, 80);
cout << endl;
int len=strlen(string);
bool flag = true;
for (int c=0; c!=len/2; c++)
{
if (flag)
{
if(string[c] != string[len-c-1])
{
flag = false;
}
}
else
{
break;
}
}
if (flag)
{
cout <<"\nThis is a Palindrome\n" << endl;
Restart = true;
continue;
}
else
{
cout << "\nThis is not a palindrome\n" << endl;
Restart = true;
continue;
}
cin.get();
}
}
I need to figure out a way to check if what the user entered is "END" in all caps, and if so, exit the program. I'm sure i can handle the exiting part, but I'm having trouble getting something that will check if the string entered is "END" in all caps.
Here is a solution that will terminate the while loop if "END" is entered. Create a helper method to do the parsing for END. Note this is very specific to the problem and not very reusable. It also is more difficult to maintain unlike Beta's solution, but you don't need to worry about maintenance until you start writing bigger programs.
bool Terminate(char* string, int len)
{
bool retval = false;
char* c = string;
if( 3 == len ) // "END\0"
{
if('E' == string[0])
{
if('N' == string [1])
{
if('D' == string[2])
{
retval = true;
}
}
}
}
return retval;
}
Then use it after int len=strlen(string); like so:
if(Terminate(string, len))
{
break; // Exit while loop
}
Make sure you declare Terminate before your main function
Is this enough of a hint?
#include <iostream>
int main()
{
char A[] = "END";
char B[10];
std::cin >> B;
std::cout << strcmp(A,B) << std::endl;
return(0);
}
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