Switch statements will not execute - c++

I have an assignment here that I've been working on for the past few hours and have been met with a problem. Whenever I compile and run the program in VS Code it throws me into an infinite loop where the text of the "menu" is printed repeatedly. I imagine this has something to do with the for(;;){ loop at the beginning of the menu.
I've deleted the for(;;){ statement at the beginning of the menu, and the continuous scrolling stopped, but I was unable to input any numbers (cases) and the program, essentially, just printed the menu and that was the end.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Student {
string name;
float GPA;
public:
string getName() const
{
return name;
}
float getGPA() const
{
return GPA;
}
void setName(string Name)
{
name = Name;
}
void setGPA(float gpa)
{
GPA = gpa;
}
Student(const string& name, float gpa)
: name(name)
, GPA(gpa)
{
}
Student()
{
}
void printDetails(Student s[], int n)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n; i++) {
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
float calcAverageGPA(Student s[], int n)
{
float avg = 0;
float sum = 0;
for (int i = 0; i <= n; i++) {
sum += s[i].getGPA();
}
avg = sum / n;
return avg;
}
float getGPAbyName(Student s[], int n, string name)
{
for (int i = 0; i <= n - 1; i++) {
if (s[i].getName() == name)
return s[i].getGPA();
}
return -1;
}
void showListByGPA(Student s[], int n, float gpa)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n - 1; i++) {
if (s[i].getGPA() > gpa)
;
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
};
int main()
{
int n = 0;
int ch;
Student s[50];
string name;
float GPA;
float avg = 0;
cout << "======================" << endl;
cout << "(1): Add a student" << endl;
cout << "(2): Print the details of a student" << endl;
cout << "(3): Get the GPA of a Student by name." << endl;
cout << "(4): Get names of students based on GPA." << endl;
cout << "(6): Quit the program." << endl;
cout << "Enter your option" << endl;
switch (ch) {
case '1':
cout << "\nEnter student's name" << endl;
cin >> name;
cout << "Enter GPA" << endl;
cin >> GPA;
s[n] = Student(name, GPA);
n++;
break;
case '2':
s[0].printDetails(s, n);
break;
case '3':
cout << "\nEnter the name of a student" << endl;
cin >> name;
GPA = s[0].getGPAbyName(s, n, name);
if (GPA == -1) {
cout << "\nStudent not found!" << endl;
}
else
cout << "\nGPA is: " << endl;
break;
case '4':
cout << "\nEnter GPA: " << endl;
cin >> GPA;
s[0].showListByGPA(s, n, GPA);
break;
case '5':
avg = s[0].calcAverageGPA(s, n);
cout << "\nAverage GPA: " << avg << endl;
break;
case '6':
exit(0);
}
}
I suspect the problem resides in main(). I included the prior blocks of the program in case they were necessary to provide any suggestions.

You obviously want to read in "ch".
You've also made this an int, and don't zero-initialize, which can cause some undefined behaviour if you don't set it beforehand.
The switch case should be
switch(X){
case 1:
// Code
break;
}
etc..
The difference is "1" or 1. It evaluates an enumeration value, instead of strings.
For safety: you might want to add a case default, which is common practice.

Related

C++ Incrementing Object Counter and Multiple Object Creation Issue

I was wondering if someone could help me on figuring out how to create multiple structs and also counting the number of structs created.
My Code follows three blocks, header file, Television file and then the main file.
Television.h
#include <iostream>
#include <string>
using namespace std;
class Televison {
string Manufacturer;
string Type; //Plasma, LCD
string Model; //Smart, regular
string Connection; //HDMI, VGA
string Power;
double Price;
int Serial_Number;
int Screen_size;
int Resolution; //larger one, so 1920 and etc.
int Channel; //any number
int Volume; //0 - 100
public:
//constructor
Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume);
//Destructor
~Televison();
//Accessor Methods
string get_Manufacturer();
string get_Type();
string get_Model();
string get_Connection();
string get_Power();
double get_Price();
int get_Serial_Number();
int get_Screen_size();
int get_Resolution();
int get_Channel();
int get_Volume();
//mutator methods
string input_Manufacturer(string Manufacturer);
string input_Type(string Type);
string input_Model(string Model);
string input_Connection(string Connection);
string input_Power(string Power);
double input_Price(double Price);
int input_Serial_Number(int Serial_Number);
int input_Screen_size(int Screen_size);
int input_Resolution(int Resolution);
int input_Channel(int Channel);
int input_Volume(int Volume);
string change_Power(string Power);
int change_Channel(int Channel);
int change_Volume(int Volume);
};
static int num_tel = 1; //number of Televisons that will be incremented
Television.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
//constructor
Televison::Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume) {
this->Manufacturer = Manufacturer;
this->Type = Type;
this->Model = Model;
this->Connection = Connection;
this->Power = Power;
this->Price = Price;
this->Serial_Number = Serial_Number;
this->Screen_size = Screen_size;
this->Resolution = Resolution;
this->Channel = Channel;
this->Volume = Volume;
num_tel++;
// initiliazes the variables to default values
Manufacturer = "Sony";
Type = "Smart";
Model = "Plasma";
Connection = "HDMI";
Power = "ON";
Serial_Number = 1234;
Price = 199.00;
Screen_size = 50;
Resolution = 1440;
Channel = 100;
Volume = 100;
}
//Destructor
Televison::~Televison() {
cout << "The " << Manufacturer << " " << Model << " has finished shutting down." << endl;
num_tel--;
cout << "The inventory of television is now: " << num_tel << endl;
}
//Get Methods
string Televison::get_Manufacturer() {
return Manufacturer;
}
string Televison::get_Model() {
return Model;
}
string Televison::get_Type() {
return Type;
}
int Televison::get_Serial_Number() {
return Serial_Number;
}
string Televison::get_Connection() {
return Connection;
}
string Televison::get_Power() {
return Power;
}
double Televison::get_Price() {
return Price;
}
int Televison::get_Screen_size() {
return Screen_size;
}
int Televison::get_Resolution() {
return Resolution;
}
int Televison::get_Channel() {
return Channel;
}
int Televison::get_Volume() {
return Volume;
}
//mutator methods
int Televison::change_Channel(int Channel1) {
if (Channel > 0)
{
Channel = Channel1;
return Channel;
}
else
{
cout << "Invalid Channel, please enter another number" << endl;
return Channel;
}
}
int Televison::change_Volume(int Volume1) {
if (Volume1 > 0)
{
Volume = Volume1;
return Volume;
}
else
{
cout << "Invalid volume, please enter another number" << endl;
return Volume;
}
}
string Televison::change_Power(string Power1) {
if (Power1 =="Y")
{
Power = Power1;
return Power;
}
else
{
return Power;
}
}
string Televison::input_Connection(string Connection1) {
Connection = Connection1;
return Connection;
}
string Televison::input_Type(string M) {
Type = M;
return Type;
}
string Televison::input_Manufacturer(string M) {
Manufacturer = M;
return Manufacturer;
}
/*
string Televison::Manufacturer_code(string M,string N) {
string J = M.substr(0,4);
string Manufacturer_code = J + N;
return Manufacturer_code;
}
*/
string Televison::input_Model(string M) {
Model = M;
return Model;
}
string Televison::input_Power(string M) {
Power = M;
return Power;
}
double Televison::input_Price(double M) {
Price = M;
return Price;
}
int Televison::input_Serial_Number(int M) {
Serial_Number = M;
return Serial_Number;
}
int Televison::input_Screen_size(int M) {
Screen_size = M;
return Screen_size;
}
int Televison::input_Resolution(int M) {
Resolution = M;
return Resolution;
}
int Televison::input_Channel(int M) {
Channel = M;
return Channel;
}
int Televison::input_Volume(int M) {
Volume = M;
return Volume;
}
Source.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
void displayStatus(Televison& Televison) {
cout << "Inventory of Televisons: " << num_tel << endl;
cout << "The Televison serial number: " << Televison.get_Serial_Number() << " " << Televison.get_Manufacturer() << " " << Televison.get_Model() << " " << Televison.get_Type() << " with " << Televison.get_Connection() << " ";
cout << "\n with " << Televison.get_Power() << " " << Televison.get_Price() << " with " << Televison.get_Screen_size() << " screen size " << Televison.get_Resolution() << "p " << "with " << Televison.get_Channel() << " channel " << Televison.get_Volume() << " Volume " << endl;
}
int main() {
{
Televison Televison_1("Sony", "Smart", "Plasma", "HDMI", "ON", 199.00, 1234, 50, 1440, 100, 100); //default Televison
cout << "This is the Televison program for personal Televison: " << endl;
bool repeat = true;
do {
cout << "Please enter the Manufacturer for the Televison: " << endl;
string Manufacturer;
getline(cin, Manufacturer);
int M1 = Manufacturer.length();
if (M1 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Manufacturer(Manufacturer);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Type of the Televison: " << endl;
string Type;
getline(cin, Type);
int M3 = Type.length();
if (M3 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Type(Type);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Model for the Televison: " << endl;
string Model;
getline(cin, Model);
int M2 = Model.length();
if (M2 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Model(Model);
} while (!repeat);
cout << "Please enter the Connection for the Televison: " << endl;
string Connection;
cin >> Connection;
Televison_1.input_Connection(Connection);
cout << "Enter the Serial Number: " << endl;
int inp4;
cin >> inp4;
Televison_1.input_Serial_Number(inp4);
cout << "Enter the Screen size: " << endl;
cin >> inp4;
Televison_1.input_Screen_size(inp4);
cout << "Enter the Resolution: " << endl;
cin >> inp4;
Televison_1.input_Resolution(inp4);
int a = 0;
while (a < 1)
{
cout << "Please enter the Price for the Televison: " << endl;
double Price;
cin >> Price;
if (Price > 0) //address speed must be greater than 0
{
Televison_1.input_Price(Price);
a++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int b = 0;
while (b < 1)
{
cout << "Would you like to Power your Televison? (Y/N)" << endl;
char input1;
cin >> input1;
if (input1 == 'Y' || input1 == 'y')
{
Televison_1.change_Power("ON");
b++;
}
else if (input1 == 'N' || input1 == 'n')
{
Televison_1.change_Power("OFF");
b++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int n = 0;
int n1 = 0;
while (n < 1)
{
cout << "Would you like to change any of the following attributes of your Televison? (Y/N)";
string input2, input3;
int input4;
double input5;
cin >> input2;
if (input2 == "Y" || input2 == "y")
{
while (n1 < 1) {
cout << "Which Televison attribute would you like to change? (Enter the respective number): " << endl;
cout << "1: Manufacturer" << endl;
cout << "2: Type" << endl;
cout << "3: Model" << endl;
cout << "4: Serial Number" << endl;
cout << "5: Connection" << endl;
cout << "6: Power" << endl;
cout << "7: Channel" << endl;
cout << "8: Screen size" << endl;
cout << "9: Resolution" << endl;
cout << "10: Volume" << endl;
cout << "11: Price" << endl;
int choice;
cin >> choice;
bool repeat1 = true;
bool repeat2 = true;
bool repeat3 = true;
switch (choice)
{
case 1:
cout << "Enter the Manufacturer: " << endl;
cin >> input3;
Televison_1.input_Manufacturer(input3);
break;
case 2:
cout << "Enter the Type: " << endl;
cin >> input3;
Televison_1.input_Type(input3);
break;
case 3:
cout << "Enter the Model: " << endl;
cin >> input3;
Televison_1.input_Model(input3);
break;
case 4:
cout << "Enter the Serial Number: " << endl;
cin >> input4;
Televison_1.input_Serial_Number(input4);
break;
case 5:
cout << "Enter the Connection: " << endl;
cin >> input3;
Televison_1.input_Connection(input3);
break;
case 6:
cout << "Enter the power: " << endl;
cin >> input3;
Televison_1.input_Power(input3);
break;
case 7:
cout << "Enter the Channel " << endl;
cin >> input4;
Televison_1.input_Channel(input4);
break;
case 8:
cout << "Enter the Screen size: " << endl;
cin >> input4;
Televison_1.input_Screen_size(input4);
break;
case 9:
do {
cout << "Enter the Resolution: " << endl;
cin >> input4;
if (input4 < 0)
{
cout << "Please enter a speed above 0" << endl;
repeat1 = false;
}
else
{
Televison_1.input_Resolution(input4);
repeat1 = true;
}
} while (!repeat1);
break;
case 10:
do {
cout << "Enter the Volume: " << endl;
cin >> input4;
if (input4 >= 0) {
cout << "Please enter a valid volume" << endl;
repeat2 = false;
}
else
{
repeat2 = true;
Televison_1.change_Volume(input4);
}
} while (!repeat2);
break;
case 11:
do {
cout << "Enter the Price: " << endl;
cin >> input5;
if (input5 > 0)
{
Televison_1.input_Price(input5);
repeat3 = true;
}
else
{
cout << "Please enter a valid price" << endl;
repeat3 = false;
}
} while (!repeat3);
break;
}
displayStatus(Televison_1);
cout << "Would you like to change another attribute? (Y/N)" << endl;
cin >> input3;
if (input3 == "Y" || input3 == "y")
{
}
else
n1++;
}
n++;
}
else if (input2 == "N" || input2 == "n")
{
cout << "The Televison will begin to shut down." << endl;
n++;
displayStatus(Televison_1);
}
else
cout << "Invalid, enter again." << endl;
}
}
// object goes out of scope - the destructor which shuts down the Televison
system("pause");
return 0;
}
Basically, my code only allows me to create one object and modify it. However, I would like to add the ability to create multiple objects and have a counter for it. I tried adding a counter, but it seems that doesn't work very well... I don't need someone to solve it, but if someone could point me to the right direction, that would be great.

Program Ends unexpectedly after the function is called

I have to write a program for bank.The classes if you will say I will provide but the problem is here,
My Problem is that in my main program I first call a function called BankProgram(); But there are other statements in the function after the function is being called The below code isnt executed at all
cout << "Enter y for opening menu again and n for exiting\t";
cin >> option;
while (option != 'y' || option != 'n')
{
cout << "Enter right value Please! only y or n: ";
char option1;
cin >> option1;
if (option1 == 'y' || option1 == 'n')
{
break;
}
}
if (option == 'y')
{
goto label;
}
else if (option == 'n')
{
cout << "The program is ending now! ";
}
Although I want to display the menu again for the user to do anything in the bank but the program terminates and exits I dont know why.I think there is a problem with object lifetime but I think that must not be the problem
Any help is appreciated.
This is the AddAccount Class
#pragma once
#include<iostream>
#include<string>
#include <vector>
using namespace std;
class Accounts
{
vector<int> Account_ID;
vector<string> AccountType;
vector<int> Customer_ID;
vector<int> Account_Balance;
public:
Accounts();
void WithDraw(int);
void Deposit(int,string,int,int);//Also can be named as add Account
void Balance();
void DeleteAccount(int);
int getAccountsNumber();
};
//Definning classes methods
Accounts::Accounts()
{
//no need to initialize vectors.They work perfect without initializing.C++ has done work for it
}
void Accounts::Deposit(int AID,string AT,int CID,int AB)
{
this->Account_ID.push_back(AID);
this->AccountType.push_back(AT);
this->Customer_ID.push_back(CID);
this->Account_Balance.push_back(AB);
}
void Accounts::WithDraw(int index)
{
cout << "\nThe Account ID of " << (index + 1) << " person is equal to: "
<< this->Account_ID[index] << endl;
cout << "\nThe Account Type of " << (index + 1) << " person is equal to: "
<< this->AccountType[index] << endl;
cout << "\nThe Customer ID of " << (index + 1) << " person is equal to: "
<< this->Customer_ID[index] << endl;
cout << "\nThe Account Balance of " << (index + 1) << " person is equal to: "
<< this->Account_Balance[index] << endl;
}
void Accounts::DeleteAccount(int index)
{
Account_ID.erase(Account_ID.begin()+index);
AccountType.erase(AccountType.begin()+index);
Customer_ID.erase(Customer_ID.begin()+index);
Account_Balance.erase(Account_Balance.begin()+index);
//Displaying that the account is successfully removed from the bank
cout << "\nThe Account ID of " << (index + 1) << " was successfully removed from the bank";
cout << "\nThe Account Type of " << (index + 1) <<" was successfully removed from the bank";
cout << "\nThe Customer ID of " << (index + 1) << " was successfully removed from the bank";
cout << "\nThe Account Balance of " << (index + 1) << " was successfully removed from the bank";
}
//It will display all the balance in the bank
void Accounts::Balance()
{
//The static int is not changed on the iteration where ever used in the loop or where ever
static int sum = 0;//To store the sum of all balance
for (unsigned int i = 0; i < Account_Balance.size(); i++)
{
sum = sum + Account_Balance[i];
}
cout << "The total balance in the bank is equal to : " << sum;
}
int Accounts::getAccountsNumber()
{
return Account_ID.size();
}
This is the Customer Class
#pragma once
#include<string>
using namespace std;
#include"Accounts.h"
#include"Manager.h"
class Customer
{
vector<string> Name;
vector<int> ID;
public:
Customer();
void AddCustomer(string,int);
void PrintAllCustomersData();
void DeleteCustomer(int);
void Print_CustomerDetails(int);
string getCustomerName(int);
};
void Customer::AddCustomer(string n, int id)
{
this->Name.push_back(n);
this->ID.push_back(id);
cout << "\nThe customer " << n << "with Id: " << id << " was successfully added in the Bank.";
}
void Customer::PrintAllCustomersData()
{
for (unsigned int i = 0; i < ID.size(); i++)
{
cout << "\nThe ID of " << (i + 1) << "Customer is : " << ID[i] << " and NAME is : " << Name[i];
}
}
void Customer::DeleteCustomer(int index)
{
Name.erase(Name.begin() + index);
ID.erase(ID.begin() + index);
cout << "\nThe customer with Name : " << Name[index] << " and ID: " << ID[index] << " was successfully deleted\n";
}
void Customer::Print_CustomerDetails(int index)
{
cout << "The Customer Name is : " << Name[index] << endl;
cout << "The Id of Customer is : " << ID[index] << endl;
}
string Customer::getCustomerName(int index)
{
return (Name[index]);
}
This is the Manager Class
#pragma once
#include<iostream>
#include<string>
using namespace std;
class Manager
{
string Name;
string Branch;
int ID;
public:
void Print_ManagerDetails();
friend ostream& operator<<(ostream&, const Manager& M);
friend istream& operator>>(istream&, Manager& M);
};
void Manager::Print_ManagerDetails()
{
cout << "\nThe ID of Manager is : " << ID << endl;
cout << "\nThe Name of Manager is : " << Name << endl;
cout << "\nThe Branch of Manager is : " << Branch << endl;
}
istream& operator>>(istream& input, Manager& M) {
input >> M.ID >> M.Name>>M.Branch;
return input;
}
ostream& operator<<(ostream& output, const Manager& M) {
output << "\nThe ID of Manager is : " << M.ID<<endl;
output << "\nThe Name of Manager is : " << M.Name << "\nThe Branch of Manager is : " << M.Branch<<endl;
return output;
}
This is the Bank Class
#pragma once
#include"Customer.h"
#include"Accounts.h"
class Bank
{
Customer* customers_ptr;
Accounts* Accounts_ptr;
Manager manager;
public:
Bank();
void AddAccount(int,string,int,int);
void DeleteAccount(int);
void AddCustomer(string,int);
void DeleteCustomer(int);
int GetNoOfAccounts();
string GetCustomer_Name(int);
};
Bank::Bank()
{
cout << "\nThe program is in the bank class\n";
}
void Bank::AddAccount(int AID, string AT, int CID, int AB)
{
Accounts_ptr->Deposit(AID, AT, CID, AB);
}
void Bank::DeleteAccount(int index)
{
Accounts_ptr->DeleteAccount(index);
}
void Bank::AddCustomer(string name, int ID)
{
customers_ptr->AddCustomer(name, ID);
}
void Bank::DeleteCustomer(int index)
{
customers_ptr->DeleteCustomer(index);
}
int Bank::GetNoOfAccounts()
{
int num=Accounts_ptr->getAccountsNumber();
return num;
}
string Bank::GetCustomer_Name(int index)
{
string name = customers_ptr->getCustomerName(index);
return name;
}
This is the main program
#include<iostream>
#include<string>
#include<conio.h>
#include<algorithm>
#include"Bank.h"
#include"Customer.h"
#include"Manager.h"
#include"Accounts.h"
using namespace std;
void BankProgram();
void BankProgram()
{
Bank b1;
Accounts A1;
Manager m1;
char options;
cout << "\n\nEnter what you want to do \n1 for entering the managers data,\n2 for showing the managers data "
<< "\n3 for adding a customer in the bank\n4 for adding an account in the bank \n5 for deleting the customer\n"
<< "\n5 for deleting the account\n6 for getting customer name\n7 for getting No. of accounts"
<< "\n8 for seeing all the balance in the bank\nPress 'e' for exit";
cin >> options;
switch (options)
{
case '1':
{
//The manager class data
cout << "\nEnter the name,ID,Branch Of Manager: ";
cin >> m1;
break;
}
case '2':
{
cout << "\nThe data of Manager is :" << m1;
break;
}
case '3':
{
string Cname;
int CID;
cout << "\nEnter the name of customer: ";
cin >> Cname;
cout << "\nEnter the Customer ID: ";
cin >> CID;
b1.AddCustomer(Cname, CID);
break;
}
case '4':
{
int AID;
int CID;
int AB;
string AT;
cout << "\nEnter the name of Account ID: ";
cin >> AID;
cout << "\nEnter the name of Customer ID: ";
cin >> CID;
cout << "\nEnter the name of Account BALANCE: ";
cin >> AB;
cout << "\nEnter the name of Account Type: ";
cin >> AT;
b1.AddAccount(AID, AT, CID, AB);
break;
}
case '5':
{
int index;
cout << "\nEnter the customer which you want to delete: ";
cin >> index;
b1.DeleteCustomer(index);
break;
}
case '6':
{
int index;
cout << "\nEnter the account which you want to delete: ";
cin >> index;
b1.DeleteAccount(index);
break;
}
case '7':
{
int cn;
cout << "\nEnter the customer ID which you want to get name: ";
cin >> cn;
b1.GetCustomer_Name(cn);
break;
}
case '8':
{
b1.GetNoOfAccounts();
break;
}
case '9':
{
A1.Balance();
break;
}
case 'e':
{
cout << "The program is ending now: ";
break;
}
default:
{
cout << "\n\nEnter right value please: \n";
}
}
}
int main()
{
// BankProgram();
bool flag = true;
char option;
label:
BankProgram();
cout << "Enter y for opening menu again and n for exiting\t";
cin >> option;
while (option != 'y' || option != 'n')
{
cout << "Enter right value Please! only y or n: ";
char option1;
cin >> option1;
if (option1 == 'y' || option1 == 'n')
{
break;
}
}
if (option == 'y')
{
goto label;
}
else if (option == 'n')
{
cout << "The program is ending now! ";
}
}
Well it turns out to be very simple
Bank::Bank()
{
cout << "\nThe program is in the bank class\n";
}
void Bank::AddAccount(int AID, string AT, int CID, int AB)
{
Accounts_ptr->Deposit(AID, AT, CID, AB);
}
Accounts_ptr is an uninitialised pointer, using it results in a program crash. You must give Accounts_ptr a value in the Bank constructor.
You have the same issue with customers_ptr.

Arrays Lose Value Upon Return (Inventory/Menu Program) C++

So for the most part I understand what I did wrong, the issue is I don't know how to fix it.
Goal: This is a store management system that must include a menu and inventory management functions that can be manipulated. To do this I used arrays to add the store's items, their descriptions, and their quantities. All the arrays are partially filled to the third element and have a max value of ten elements.
Issue: When the program is run the first time it works and the user can see their inventory, description and quantity. However when they exit to the menu and come BACK to inventory, everything past the third element is cleared. This is due to the declarations initializing the arrays past the third element to 0. How do I fix this to guarantee the user has their inventory saved and can view it upon return?
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
//declarations
int mainMenu(); //done
void inventoryMgmt();
void addInv(); //working on
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void customerReciept(); //done
void calculatePrice(); //done
void exit(); //done
const double massTax = 0.0625;
//main
int main() {
int choice;
bool repeat = true;
while (repeat = true) {
choice = mainMenu();
switch (choice) {
case 1:
customerReciept();
break;
case 2:
inventoryMgmt();
break;
//case 3:
//itemSearcher();
//break;
case 4:
exit();
repeat = false;
break;
}
}
return 0;
}
//main menu function ***done
int mainMenu() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Main Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Customer Reciept" << endl;
cout << "\t\t\t\t\t\t 2. Inventory Management" << endl;
cout << "\t\t\t\t\t\t 3. Item Search" << endl;
cout << "\t\t\t\t\t\t 4. Exit" << endl << endl;
int choice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> choice;
while (choice < 1 || choice > 4) {
cout << "\t\t\t\t\t Incorrect Selection Please Select Again: ";
cin >> choice;
}
return choice;
}
//customer reciept function **done
void customerReciept() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Receipt Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Calculate Receipt" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
int recieptChoice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> recieptChoice;
while (recieptChoice < 1 || recieptChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> recieptChoice;
}
if (recieptChoice == 1) {
calculatePrice();
}
}
void calculatePrice() {
double cost;
double taxAmount;
int numOfItems;
double finalCost = 0;
char tax;
int i;
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "How many items were purchased?: ";
cin >> numOfItems;
for (i = 0; i < numOfItems; i++) {
cout << "What did item " << i + 1 << " cost? $";
cin >> cost;
cout << "Is this item taxable? (y/n):";
cin >> tax;
if (tax == 'y' || tax == 'Y') {
taxAmount = (cost * massTax);
cost = taxAmount + cost;
finalCost = cost + finalCost;
}
else {
finalCost = cost + finalCost;
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "This customer's total is $" << finalCost << endl;
}
void inventoryMgmt() {
int invChoice;
cout << "\n\n\t\t\t\t\t Welcome to Inventory Management " << endl;
cout << "\t\t\t\t ______________________________________________ \n\n";
cout << "\t\t\t\t\t Inventory Settings: " << endl;
cout << "\t\t\t\t\t\t 1. Add/View & Edit/Delete Inventory" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> invChoice;
cout << endl << endl;
while (invChoice < 1 || invChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> invChoice;
}
if (invChoice == 1) {
addInv();
}
if (invChoice == 2) {
//edit/delete();
}
}
void addInv() {
//so when this is called, everything is initialized to 0 which makes it wipe the memory
//when the user comes back to it from the menu.
const int description = 20; //this allows a short description for each item
const int counter = 10; //slots of inventory allowed
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "Hot Drinks", "Cold Drinks", "Books"};
string descriptionArray[description] = { "Coffee, Tea etc", "Water, juice, etc", "Texts, notebook, etc"};
char addChoice;
int destination;
cout << "\t\t\t\t\t\t 1. Add/View" << endl;
cout << "\t\t\t\t\t\t 2. Edit/Delete" << endl;
cout << "\t\t\t\t\t\t 3. Exit to Main" << endl;
cout << "\t\t\t\t\t\t Where would you like to go?: " << endl;
cin >> destination;
while (destination < 1 || destination > 3) {
cout << "Invalid Selection, Please Select Again: ";
cin >> destination;
}
if (destination == 1) {
cout << "Would you like to add an item? (y/n): ";
cin >> addChoice;
int i = 3; //these two are initialized to three to ensure that the store
int ii = 3; //will always have hot drinks, cold drinks and books as options
while (addChoice == 'y' && i < counter) {
cout << "What would you like to add?: ";
cin >> itemArray[i];
cout << "You have added \"" << itemArray[i] << "\" to the inventory\n";
cout << "Please Provide a Brief Description: ";
cin.ignore();
getline(cin, descriptionArray[ii]);
cout << "You've described \"" << itemArray[i] << "\" as \"" << descriptionArray[i] << "\"" << endl;
cout << "What is the quantity of " << itemArray[i] << " in stock?";
cin >> quantity[i];
cout << "Would you like to add another item?";
cin >> addChoice;
i++;
ii++;
if (i > counter) {
cout << "**INVENTORY LIMIT REACHED*** ";
}
}
invView(itemArray, 10, descriptionArray, 10, quantity, 10); //working on this. //so use this for view, edit, and delete.
}
}
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) { //add quantity
int i = 0;
int ii = 0;
int iii = 0;
cout << "Your inventory consists of: ";
while (i < sizeofArray && x[i] != "" && ii < secondArray && y[i] != "" && iii < thirdArray) {
cout << x[i] << " - " << y[i] << " | Quantity: " << z[i] << endl;
i++;
ii++;
}
}
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) {
cout << "Which item would you like to edit?";
}
void exit() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t Thank you for using the Massasoit Store Management System" << endl;
exit(1);
}
I included the entire code in case it was needed. The issues are centered around the inventoryMgmt() and addInv() functions.
Thanks in advance for any help!
In theaddInv() all the arrays are local. Once that function is done executing, all local variables are freed up thus resulting in your deletion. Try place them outside your addInv() function:
int main(){
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "..."};
string descriptionArray[description] = { "..."};
void addInv() {...}
}

How to get grade average and do a search method?

I have been working on this project for days now and I got most of it down however there are three problems that I am having. I am trying to calculate the average grade from a ifstream file, the program reads it successfully however when I pass the array from one function to another, it just displays 0 and F as I am trying to display the percentage and letter grade.
My second question is how do I get the array to only print out elements that are populated. So if I create an array of 10 and only populate the first three elements, how would I got to only get those first three elements to print only?
And my other question is when I try doing a search, it keeps saying record not found even I typed the name correctly. The record is being search by last name.
Any pointers or help would be greatly appreciated. Thanks!
My code:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
void greeting(string[], string[], double[], double[], double[], int);
int getinfo(string[], string[], double[], double[], double[], int);
int calculateaverageandgrade(string[], string[], double[], double[], double [], int);
void sortandsearch(string[], string[], double[], double[], double[], int);
void goodbye(string[], string[], double[], double[], double[]);
int main() {
string fname[10] = { "" };
string lname[10] = { "" };
double grade[10] = { 0 };
double grade2[10] = { 0 };
double grade3[10] = { 0 };
const int arraysize = 10;
greeting(fname, lname, grade, grade2, grade3, arraysize);
getinfo(fname, lname, grade, grade2, grade3, arraysize);
calculateaverageandgrade(fname, lname, grade, grade2, grade3, arraysize);
system("pause");
return 0;
}
void greeting(string fname[], string lname[], double grade[], double grade2 [], double grade3[], int arraysize) {
int choice = int();
char cont = 'y';
while (cont == 'y' || cont == 'Y')
{
cout << setw(60) << "Main Menu" << endl;
cout << setw(66) << "======================" << endl;
cout << "\t\t\t\tToday we will be calculating grades from a file" << endl << "\t\t\t\tthat you can provide for us using notepad." << endl << "\t\t\t\tBe sure to update your file every time you run the program" << endl;
cout << endl;
cout << setw(64) << "Reading file...." << endl;
cout << setw(66) << "======================" << endl;
cout << endl << endl << endl;
cout << setw(65) << "1. Calculate Grades." << endl;
cout << setw(63) << "2. Search Grades" << endl;
cout << setw(68) << "2. Exit from the Program." << endl;
cout << endl;
cout << setw(70) << "Please Enter your Selection: ";
cin >> choice;
if (cin.fail())
{
cout << "Invalid selection" << endl;
cin.clear();
cin.ignore(1000, '\n');
}
else
{
if (choice == 1)
{
calculateaverageandgrade(fname, lname, grade, grade2, grade3, arraysize);
}
else if (choice == 2) {
sortandsearch(fname, lname, grade, grade2, grade3, arraysize);
}
else if (choice == 3)
{
goodbye(fname, lname, grade, grade2, grade3);
}
else
{
cout << "Invalid Selection!" << endl;
}
}
cout << "\nDo you want to continue (Y/N)....";
cin >> cont;
}
}
int getinfo(string fname[], string lname[],double grade[], double grade2[], double grade3[], int arraysize) {
system("cls");
ifstream in;
in.open("data.txt");
int i = 0;
while (!in.eof()) {
in >> fname[i] >> lname[i] >> grade[i] >> grade2[i] >> grade3 [i];
++i;
}
arraysize = i;
return arraysize;
}
int calculateaverageandgrade(string fname[], string lname[], double grade[], double grade2[], double grade3[], int arraysize) {
system("cls");
const int i = 10;
double total[i];
for (int a = 0; a < arraysize; ++a) {
cout << "Name:" << setw(20) << "Score: " << setw(20) << "Grade: " << endl;;
cout << fname[a] << " " << lname[a];
total[a] = grade[a] + grade2[a] + grade3[a];
total[a] = total[a] / 3;
cout << setw(20) << total[a] << endl;
if (total[a] >= 90) {
cout << setw(40) << "A" << endl;
}
else if (total[a] >= 80) {
cout << setw(41) << "B" << endl;
}
else if(total[a] >= 70) {
cout << setw(41) << "C" << endl;
}
else if (total[a] >= 60) {
cout << setw(41) << "D" << endl;
}
else {
cout << setw(41) << "F" << endl;
}
}
system("pause");
return total[i];
}
void sortandsearch(string fname[], string lname[], double grade[], double grade2[], double grade3[], int arraysize) {
system("cls");
string nameSearch = string();
int i = int();
bool flag = false;
char key = char();
system("cls");
cout << "\nEnter Name to be Searched: ";
cin >> nameSearch;
while (i<arraysize)
{
if (lname[i] == nameSearch)
{
cout << "Record Found --- ";
cout << "Record # " << i + 1 << " contains " << nameSearch << "'s information." << endl;
flag = true;
}
++i;
}
if (flag == false)
{
cout << "\nRecord Not Found!" << endl;
}
cout << "\n\n\nPress any Key to Continue...";
key = _getch();
}
void goodbye(string fname[], string lname[], double grade[], double grade2[], double grade3[]) {
system("cls");
cout << setw(70) << "Thanks for using my program!" << endl;
system("pause");
exit(1);
}

Data not storing to be displayed?

I am a beginner taking a programming class and I am having trouble with my assignment. I am to make a program that can store and sort data(I chose games), and everything seems to be going alright. EXCEPT for when I choose to input a game, and later display the games I've entered, there will be nothing in the list. Is there something I'm missing?
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct VidyaGames {
string Title;
string Date;
string Developer;
};
void getGames(VidyaGames array[], int &k);
void displayGames(VidyaGames array[], int &k);
void deleteGames(VidyaGames array[], int &k);
void sortGames(VidyaGames array[], int &k);
const int MAX = 150;
string Title;
string Date;
string Developer;
int main()
{
char choice;
VidyaGames array[MAX];
bool kek = true;
int k = 0;
do
{
cout << "Welcome to the 'Super Incredible Amazing Game Storage-o-Tron 5000(and one)." << endl;
cout << " " << endl;
cout << "Please select which task you would like to perform by typing in the " << endl;
cout << "corresponding letter in the bracket: " << endl;
cout << " " << endl;
cout << "[I]nput a game into the list." << endl;
cout << "[D]isplay the games you have stored." << endl;
cout << "[S]ort the games you have stored." << endl;
cout << "[R]emove a game from the list." << endl;
cout << "[Q]uit the program." << endl;
cin >> choice;
switch (choice)
{
case 'I': getGames(array, k); break;
case 'D': displayGames(array, k); break;
case 'S': deleteGames(array, k); break;
case 'R': deleteGames(array, k); break;
case 'Q': kek = false; break;
default : cout << "Hey. Remember when I gave you the specific options you were allowed to choose?" << endl;
cout << "Maybe enter one of those?" << endl;
cout << " " << endl;
}
}
while (kek);
cout << "You have killed me." << endl;
}
void getGames(VidyaGames array[], int &k)
{
system("cls");
VidyaGames tmp;
char lel[100];
cout << "Enter the title of your game: " << endl;
getline (cin, Title);
cout << "Enter the date your game was published: (Example: March 15th, 2014)" << endl;
getline (cin, Date);
cout << "Enter the developer of your game: " << endl;
getline (cin, Developer);
}
void displayGames(VidyaGames array[], int &k)
{
system ("cls");
if (k==0)
cout << "There is literally nothing in this list, as you have made the mental choice to not put anything in it yet." << endl;
else if (k > 0) {
for (int i=0; i < 0; i++)
{
cout << "Title: " << array[i].Title << endl;
cout << "Release Date: " << array[i].Date << endl;
cout << "Developer: " << array[i].Developer << endl;
}
}
}
void deleteGames(VidyaGames array[], int &k) {
system("cls");
char deleteChoice;
if (k==0)
cout << "There is literally nothing in this list, as you have made the mental choice to not put anything in it yet." << endl;
else {
cout << "Please type the name of the game you would like to delete: " << endl;
cin >> deleteChoice;
}
}
void sortGames(VidyaGames array[], int &k)
{
}
you forget to set value in your array.
i add 4 lines to function getGames:
array->Title = Title;
array->Date = Date;
array->Developer = Developer;
k++;
and change one line in function displayGames:
for (int i=0; i < k; i++)
this is final code:
// test_3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct VidyaGames {
string Title;
string Date;
string Developer;
};
void getGames(VidyaGames array[], int &k);
void displayGames(VidyaGames array[], int &k);
void deleteGames(VidyaGames array[], int &k);
void sortGames(VidyaGames array[], int &k);
const int MAX = 150;
string Title;
string Date;
string Developer;
int main()
{
char choice;
VidyaGames array[MAX];
bool kek = true;
int k = 0;
do
{
cout << "Welcome to the 'Super Incredible Amazing Game Storage-o-Tron 5000(and one)." << endl;
cout << " " << endl;
cout << "Please select which task you would like to perform by typing in the " << endl;
cout << "corresponding letter in the bracket: " << endl;
cout << " " << endl;
cout << "[I]nput a game into the list." << endl;
cout << "[D]isplay the games you have stored." << endl;
cout << "[S]ort the games you have stored." << endl;
cout << "[R]emove a game from the list." << endl;
cout << "[Q]uit the program." << endl;
cin >> choice;
switch (choice)
{
case 'I': getGames(array, k); break;
case 'D': displayGames(array, k); break;
case 'S': deleteGames(array, k); break;
case 'R': deleteGames(array, k); break;
case 'Q': kek = false; break;
default : cout << "Hey. Remember when I gave you the specific options you were allowed to choose?" << endl;
cout << "Maybe enter one of those?" << endl;
cout << " " << endl;
}
}
while (kek);
cout << "You have killed me." << endl;
}
void getGames(VidyaGames array[], int &k)
{
system("cls");
VidyaGames tmp;
char lel[100];
cout << "Enter the title of your game: " << endl;
getline (cin, Title);
cout << "Enter the date your game was published: (Example: March 15th, 2014)" << endl;
getline (cin, Date);
cout << "Enter the developer of your game: " << endl;
getline (cin, Developer);
array->Title = Title;
array->Date = Date;
array->Developer = Developer;
k++;
}
void displayGames(VidyaGames array[], int &k)
{
system ("cls");
if (k==0)
cout << "There is literally nothing in this list, as you have made the mental choice to not put anything in it yet." << endl;
else if (k > 0) {
for (int i=0; i < k; i++)
{
cout << "Title: " << array[i].Title << endl;
cout << "Release Date: " << array[i].Date << endl;
cout << "Developer: " << array[i].Developer << endl;
}
}
}
void deleteGames(VidyaGames array[], int &k) {
system("cls");
char deleteChoice;
if (k==0)
cout << "There is literally nothing in this list, as you have made the mental choice to not put anything in it yet." << endl;
else {
cout << "Please type the name of the game you would like to delete: " << endl;
cin >> deleteChoice;
}
}
void sortGames(VidyaGames array[], int &k)
{
}