The issue I am having is that I am storing values into my vectors and concatenating them into one bundle of vectors. However, when I go back into the class where I stored the values, they are gone. VS then throws up a generic error. Please find my code below.
#include <vector>
#include <conio.h>
#include <cctype>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
void Train_Time_Entries();
struct
{
int iOption, iCount = 0;
int myContNo = -1;
int fDecide = -1;
string AdminUser, AdminPass;
vector <string> AdminUsers{ "John1966", "Christine55", "BlakeBennett74", "SarahHarding93", "Connor1987" };
vector <string> AdminPasswords{ "KalEL", "HenryDog6", "WesternRailway21", "Railwayssince89", "Budweisersaregood" };
vector <string> sAdmins;
string sLocation, sArrive, sDepart, sDay;
bool bAdmin = true, bAddEnt = true, bMenu = true, bMenu1 = true;
}iop, admus, admpa, AdminUsers, AdminPas, bAdm, sLoc, sArr, sDep, bAdd, myCo,fde, bMe, bMen, sAds,sDa,iCou;
//****************Admin Only********************
class Train_Time_Ent
{
public:
vector<string> sLocations;
vector<string> sDay;
vector<string> sArrive;
vector<string> sDepart;
vector<string> sBundle;
};
//*****************Admin Only*******************
void Train_Time_Entries()
{
system("cls");
Train_Time_Ent myobjs;
do
{
cout << " Train Entries(Admin View Only)\n";
for (int i = 0; i < 5; i++)
{
cin.ignore();
cout << "Please enter a train location: " << flush;
getline(cin, sLoc.sLocation);
myobjs.sLocations.push_back(sLoc.sLocation + "\n");
cout << "Enter a day of the week for times: " << flush;
cin >> sDa.sDay;
myobjs.sDay.push_back(sDa.sDay + "\n");
do
{
cout << "Now enter a Train Arrive time for this location: " << flush;
cin >> sArr.sArrive;
myobjs.sArrive.push_back(sArr.sArrive + "\n");
cout << "Would you like to add any more arrival times? Y=1 N=2: " << flush;
cin >> iop.iOption;
if (iop.iOption == 2)
{
cout << "Okay Thank you\n";
break;
}
} while (iop.iOption == 1);
do
{
cout << "Now enter a Train Departure time for this location: " << flush;
cin >> sDep.sDepart;
myobjs.sDepart.push_back(sDep.sDepart + "\n");
cout << "Would you like to enter more departure times? Y=1 N=2: " << flush;
cin >> iop.iOption;
if (iop.iOption == 2)
{
cout << "Okay Thank you\n";
break;
}
} while (iop.iOption == 1);
cout << "Would you like to make any other entries? Y = 1 N = 2: " << flush;
cin.ignore();
cin >> iop.iOption;
if (iop.iOption == 1)
{
bAdd.bAddEnt = true;
fde.fDecide++;
}
else if (iop.iOption == 2)
{
bAdd.bAddEnt = false;
fde.fDecide++;
break;
}
}
} while (bAdd.bAddEnt == true);
// For future entries this needs to be checked so the values are set accordingly
for (int i = myCo.myContNo; myCo.myContNo <= fde.fDecide;)
{
myCo.myContNo++;
if (myCo.myContNo <= fde.fDecide)
{
myobjs.sBundle.push_back(myobjs.sDay[myCo.myContNo] + myobjs.sLocations[myCo.myContNo] + myobjs.sArrive[myCo.myContNo] + myobjs.sDepart[myCo.myContNo]);
}
}
cout << myobjs.sBundle[0];
myCo.myContNo--;
bMe.bMenu = true;
cout << "Exiting to Admin Menu...\n";
_getch();
}
void Concatenate_Admins()
{
for (int i = 0; i < AdminUsers.AdminUsers.size(); i++)
{
sAds.sAdmins.push_back(AdminUsers.AdminUsers[i] + AdminPas.AdminPasswords[i]);
}
}
int main()
{
do
{
system("cls");
cout << " Western Railway\n";
cout << "Please choose from one of the following\n";
cout << "1:: Train Times\n";
cout << "2:: Make a Reservation\n";
cout << "3:: Make a Cancellation\n";
cout << "4:: Reserved Trains\n";
cout << "5:: Admin Login\n";
cout << "6:: Quit\n";
cin >> iop.iOption;
switch (iop.iOption)
{
case 1:
iop.iOption = 1;
//Train_Times();
case 2:
iop.iOption = 2;
//Make_A_Reservation();
case 3:
iop.iOption = 3;
//Make_A_Cancellation();
case 4:
iop.iOption = 4;
//Reserved_Trains();
case 5:
iop.iOption = 5;
Concatenate_Admins();
// Look into an option to add more admin logins after authorization of login (New Employees)
// also look into updating times for various locations
do
{
system("cls");
cout << " *******Admin Login*******\n";
cout << "Please enter Authorised credentials below;\n";
cout << "Username: " << flush;
cin >> admus.AdminUser;
cout << "Password: " << flush;
cin >> admpa.AdminPass;
iCou.iCount++;
if (find(sAds.sAdmins.begin(), sAds.sAdmins.end(), admus.AdminUser + admpa.AdminPass) != sAds.sAdmins.end())
{
cout << "Successfully Logged in...\n";
bAdm.bAdmin = false;
}
else if (find(sAds.sAdmins.begin(), sAds.sAdmins.end(), admus.AdminUser + admpa.AdminPass) == sAds.sAdmins.end())
{
cout << "Entry not recognized...\n";
cout << "No " << iCou.iCount << " of 3 Attempts\n";
bAdm.bAdmin = true;
if (iCou.iCount == 3)
{
cout << "Too many attempts made\n";
cout << "Exiting to main menu...\n";
bAdm.bAdmin = false;
}
}
_getch();
} while (bAdm.bAdmin == true);
do
{
if (iCou.iCount <= 3)
{
system("cls");
cout << " *******Admin Mode*******\n";
cout << "Please choose from one of the following; \n";
cout << "Option 1: Train Time Entries\n";
cout << "Option 2: View Reserved Lists\n";
cout << "Option 3: View Passenger Info\n";
cout << "Option 4: Return to main menu\n";
cin >> iop.iOption;
switch (iop.iOption)
{
case 1:
iop.iOption = 1;
Train_Time_Entries();
bMe.bMenu = true;
case 2:
iop.iOption = 2;
//Reserved_Lists();
bMe.bMenu = true;
case 3:
iop.iOption = 3;
//Passenger_Info();
bMe.bMenu = true;
case 4:
iop.iOption = 4;
cout << "Returning to Main Menu...\n";
bMe.bMenu = false;
break;
_getch();
}
}
else if (iCou.iCount > 3)
{
bMen.bMenu1 = true;
main();
}
} while (bMe.bMenu == true);
bMen.bMenu1 = true;
break;
case 6:
iop.iOption = 6;
cout << "Exiting Application...\n";
bMen.bMenu1 = false;
break;
}
} while (bMen.bMenu1 == true);
return 0;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I tried my best to figure this out but it was unsuccessful :C
PROBLEM
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
FULL CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <list>
#include <ctime>
using namespace std;
struct Treniruote
{
string data, laikas, vardas, pavarde, pratimai;
};
void NuskaitytiIsFailo(list<Treniruote>& treniruotes)
{
string line, word;
fstream file("planas.csv", ios::in);
if (file.is_open())
{
while (getline(file, line))
{
stringstream str(line);
Treniruote row;
if (getline(str, word, ','))
row.data = word;
if (getline(str, word, ','))
row.laikas = word;
if (getline(str, word, ','))
row.vardas = word;
if (getline(str, word, ','))
row.pavarde = word;
if (getline(str, word, ','))
row.pratimai = word;
treniruotes.push_back(row);
}
}
else
cout << "Could not open the file";
}
void rastiKlientoInfo(list<Treniruote>& treniruotes)
{
int a;
string fname, pavarde;
cout << "Write clients surname:";
cin >> pavarde;
cout << "Output to the screen press -1\n";
cout << "Output to the file press - 2\n";
cout << "Output all exercise needed to be done in a week - 3\n";
cout << "Your choice:";
cin >> a;
if (a == 2)
{
cout << "Enter the file name: ";
cin >> fname;
}
else if (a == 3)
{
cout << "Enter the file name: ";
cin >> fname;
}
else
{
}
for (Treniruote& t : treniruotes)
{
if (t.pavarde == pavarde)
{
if (a == 1)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
else if (a == 3)
{
fstream file(fname + ".csv", ios::app);
file << t.pratimai << endl;
}
else
{
fstream file(fname + ".csv", ios::app);
file << t.data << endl;
file << t.laikas << endl;
file << t.vardas << endl;
file << t.pavarde << endl;
file << t.pratimai << endl;
file << endl;
}
}
}
}
void PakeistiReiksmes(list<Treniruote>& treniruotes)
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti duomenys" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >>duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >>duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
t.vardas = t.pavarde = t.pratimai = "obolys";
}
}
}
}
void SukurtiTuscius(list<Treniruote> &treniruotes)
{
for (int i = 27; i <= 30; ++i)
{
stringstream diena;
diena << "2022.11." << i;
for (int j = 8; j <= 19; ++j)
{
stringstream valanda;
valanda << j << ":00-"<< j+1 <<":00";
Treniruote t;
t.data = diena.str();
t.laikas = valanda.str();
t.vardas = t.pavarde = t.pratimai = "nera";
treniruotes.push_back(t);
}
}
}
void ParodytiVisaTvarkarasti(list<Treniruote>& treniruotes)
{
for (Treniruote& t : treniruotes)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
void salinti_pridėti(list<Treniruote>& treniruotes)
{
}
void ProgramosPabaiga(list<Treniruote>& treniruotes)
{
fstream file("planas.csv", ios::out);
for (Treniruote& t : treniruotes)
{
file << t.data <<","<< t.laikas << "," << t.vardas << "," << t.pavarde << "," << t.pratimai;
file << endl;
}
cout << "PROGRAMA BAIGTA";
exit(0);
}
int main()
{
int choice;
bool gameOn = true;
list<Treniruote> treniruotes;
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime,&now);
auto month = to_string(1 + newtime.tm_mon);
auto day = to_string(newtime.tm_mday);
auto hour = to_string(newtime.tm_hour);
auto hour_pridėta = to_string(1 + newtime.tm_hour);
//sukuria .csv faila pagal irasyta pavadinima
//string fname;
//cout << "Enter the file name: ";
//cin >> fname;
// fstream file(fname + ".csv", ios::app);
//Menu
while (gameOn != false) {
cout << "*******************************\n";
cout << " 1 - Create empty weekly plan.\n";
cout << " 2 - Show the full schedule.\n";
cout << " 3 - Read the weekly work plan.\n";
cout << " 4 - Change the schedule field information.\n";
cout << " 5 - Find the given client's full weekly workouts\n";
cout << " 7 - Exit.\n";
cout << "*******************************\n";
for (Treniruote& t : treniruotes)
{
if (t.data == "2022." + month + "." + day)
{
if (t.laikas == hour + ":00-" + hour_pridėta + ":00")
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
}
cout << "*******************************\n";
cout << " Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
SukurtiTuscius(treniruotes);
break;
case 2:
ParodytiVisaTvarkarasti(treniruotes);
break;
case 3:
NuskaitytiIsFailo(treniruotes);
break;
case 4:
PakeistiReiksmes(treniruotes);
break;
case 5:
rastiKlientoInfo(treniruotes);
break;
case 6:
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti langeli" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >> duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >> duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
}
break;
case 7:
{
ofstream file;
file.open("planas.csv", std::ofstream::out | std::ofstream::trunc);
file.close();
ProgramosPabaiga(treniruotes);
break;
}
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
return 0;
}
You must not remove items from a list while iterating through a range-based for loop. Under the hood, the loop stores a begin and end iterator of the original list, and iterate all items between them, and attempting to remove items during the loop will make end unreachable.
Instead, you could simply use std::list::remove_if to remove all elements that satisfy a certain condition:
my_list.remove_if([a, b](const auto& element){
return element.a == a && element.b == b;
};
I am creating a hotel management system. In the book_room function the user enters a room number , the control shifts to the check function and if the room is available then it asks for some details and then books the room.
Now so that multiple rooms can be displayed in the file, I added the app mode to append the file however due to this the program didn't take input at all.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <string>
using namespace std;
struct hotel {
int room_no[51];
string name[51];
string adress[51];
int mobile_no[51];
int bill[51];
int days[51];
int room;
int room1;
int flag = 0;
fstream records;
void main_menu();
int book_rooms();
int customer_records();
int rooms_alloted();
int edit_records();
int customer_bills();
int check(int);
};
void hotel::main_menu()
{
int choice;
while (choice != 6) {
system("cls");
cout << "\n\t\t\t\t*************************";
cout << "\n\t\t\t\t HOTEL MANAGEMENT SYSTEM ";
cout << "\n\t\t\t\t * MAIN MENU *";
cout << "\n\t\t\t\t*************************";
cout << "\n\n\n\t\t\t1.Book A Room";
cout << "\n\t\t\t2.Customer Records";
cout << "\n\t\t\t3.Rooms Allotted";
cout << "\n\t\t\t4.Edit Record";
cout << "\n\t\t\t5.Customer Bills";
cout << "\n\t\t\t6.Exit";
cout << "\n\n\t\t\tEnter Your Choice: ";
cin >> choice;
switch (choice) {
case 1: {
book_rooms();
break;
}
case 2: {
customer_records();
break;
}
case 3: {
rooms_alloted();
break;
}
case 4: {
edit_records();
break;
}
case 5: {
customer_bills();
break;
}
case 6: {
break;
}
}
}
}
int hotel::book_rooms()
{
int i = 1;
char yes = 'y';
while (yes == 'y') {
system("cls");
int room;
cout << "\n\t*************************";
cout << "\n\t ROOM BOOKING";
cout << "\n\t*************************";
cout << "\n\nPlease enter the room number you want to book.";
cout << "\n1: Standard room(Room 1-20) (Rs.1000/night)";
cout << "\n2.Suite(Room 21-40) (Rs.5000/night)";
cout << "\n3.Luxury Room(Room 41-50) (Rs.10000/night)\n";
cin >> room;
flag = check(room);
ofstream records{ "rooms.txt", ios::app };
if (flag == 1) {
cout << "Sorry this room has been taken";
system("pause");
}
else {
cout << "\n";
room_no[room - 1] = room;
records << "Room " << room_no[room - 1] << "\n";
cout << "Name:";
getline(cin, name[room - 1]);
getline(cin, name[room - 1]);
records << name[room - 1] << "\n";
cout << "Adress:";
getline(cin, adress[room - 1]);
records << adress[room - 1] << "\n";
cout << "\nMobile no: ";
cin >> mobile_no[room - 1];
records << mobile_no[room - 1] << "\n ";
cout << "\nYour room has been booked\n";
cout << "Do you want to book another room\n";
cin >> yes;
}
}
system("pause");
records.close();
}
int hotel::check(int r)
{
flag = 0;
ifstream records("rooms.txt");
while (!records.eof()) {
records >> room_no[r - 1];
if (room_no[r - 1] == r) {
flag = 1;
break;
}
}
records.close();
return flag;
}
int main()
{
hotel p;
p.main_menu();
}
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.
Error 1 error LNK2005: "class bus bs" (?bs##3Vbus##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\main.obj Project17
Error 2 error LNK2005: "class ticket tick" (?tick##3Vticket##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\main.obj Project17
Error 3 error LNK2005: "class ticket tick" (?tick##3Vticket##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\ticket.obj Project17
Error 4 error LNK2005: "class bus bs" (?bs##3Vbus##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\ticket.obj Project17
Error 5 error LNK1169: one or more multiply defined symbols found c:\users\tahir\documents\visual studio 2013\Projects\Project17\Debug\Project17.exe 1 1 Project17
bus.h
#pragma once
class bus
{
int busno;
int noofkidsseats;
int noofwomenseats;
int noofmenseats;
int noofspecialseats;
int noofvvip;
char *busname;
char *startpoint;
char *destination;
public:
bus();
void input();
int rbusno();
int rnoofkidsseats();
int rnoofwomenseats();
int rnoofmenseats();
int rnoofspecialseats();
int rnoofvvip();
void display();
}bs;
bus.cpp
#include <iostream>
#include <fstream>
#include "bus.h"
#include "ticket.h"
#include "windows.h"
using namespace std;
int length(char arr[])
{
int i = 0;
for (; arr[i] != '\0'; i++);
return i;
}
void gotoxy(int x, int y)
{
static HANDLE h = NULL;
if (!h)
h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD c = { x, y };
SetConsoleCursorPosition(h, c);
}
bus::bus()
{
busno = 0;
noofkidsseats = 0;
noofwomenseats = 0;
noofmenseats = 0;
noofspecialseats = 0;
noofvvip = 0;
busname = '\0';
startpoint = '\0';
destination = '\0';
}
int bus::rbusno()
{
return busno;
}
int bus::rnoofkidsseats()
{
return noofkidsseats;
}
int bus::rnoofwomenseats()
{
return noofwomenseats;
}
int bus::rnoofmenseats()
{
return noofmenseats;
}
int bus::rnoofspecialseats()
{
return noofspecialseats;
}
int bus::rnoofvvip()
{
return noofvvip;
}
void bus::input()
{
cout << "ENTER THE BUS NUMBER: ";
cin >> busno;
cout << "ENTER THE NUMBER OF SEATS FOR KIDS: ";
cin >> noofkidsseats;
cout << "ENTER THE NUMBER OF SEATS FOR WOMEN: ";
cin >> noofwomenseats;
cout << "ENTER THE NUMBER OF SEATS FOR MEN: ";
cin >> noofmenseats;
cout << "ENTER THE NUMBER OF SEATS SPECIAL PERSONS: ";
cin >> noofspecialseats;
cout << "ENTER THE NUMBER OF SEATS FOR VVIP PASSENGERS: ";
cin >> noofvvip;
cout << "ENTER THE BUS NAME: ";
char name[20];
cin >> name;
int l = length(name);
busname = new char[l];
int i;
for (i = 0; i < l; i++)
busname[i] = name[i];
busname[i] = '\0';
cout << "ENTER THE STARTING POINT: ";
char start[20];
cin >> start;
int L = length(start);
startpoint = new char[L];
int j;
for (j = 0; j < L; j++)
startpoint[j] = start[j];
startpoint[j] = '\0';
cout << "ENTER THE DESTINATION: ";
char end[20];
cin >> end;
int s = length(end);
destination = new char[s];
int k;
for (k = 0; k < s; k++)
destination[k] = end[k];
destination[k] = '\0';
}
void bus::display()
{
cout << " ***************************************" << endl;
cout << " * *" << endl;
cout << " * BUS DEATAILS *" << endl;
cout << " * *" << endl;
cout << " ***************************************" << endl;
cout << " THE BUS NUMBER: ";
cout << busno << endl;
cout << " THE BUS NAME: ";
cout << busname << endl;
cout << " STARTING POINT: ";
cout << startpoint << endl;
cout << " DESTINATION: ";
cout << destination << endl;
cout << " THE NUMBER OF SEATS FOR KIDS: ";
cout << noofkidsseats << endl;
cout << " THE NUMBER OF SEATS FOR WOMEN: ";
cout << noofwomenseats << endl;
cout << " THE NUMBER OF SEATS FOR MEN: ";
cout << noofmenseats << endl;
cout << " THE NUMBER OF SEATS SPECIAL PERSONS: ";
cout << noofspecialseats << endl;
cout << " THE NUMBER OF SEATS FOR VVIP PASSENGERS: ";
cout << noofvvip << endl;
}
ticket.h
#pragma once
class ticket
{
int resno;
int age;
int tokids;
int towomen;
int tomen;
int tospecial;
int tovvip;
int noofkidsseats;
int noofwomenseats;
int noofmenseats;
int noofspecialseats;
int noofvvip;
char *pname;
char *status;
public:
ticket();
void reservation();
int returnresno();
void cancellation();
void print();
}tick;
ticket.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "ticket.h"
#include "bus.h"
using namespace std;
ticket::ticket()
{
resno = 0;
age = 0;
tokids = 0;
towomen = 0;
tomen = 0;
tospecial = 0;
tovvip = 0;
pname = '\0';
status = '\0';
}
int ticket::returnresno()
{
return resno;
}
void ticket::print()
{
int f = 0;
system("cls");
ifstream fn("Ticket1.dat", ios::out); fn.seekg(0);
if (!fn)
{
cout << "ERROR IN THE FILE ";
}
X:
cout << "ENTER THE RESERVATION NO ";
int n;
cin >> n;
while (!fn.eof())
{
fn.read((char*)&tick, sizeof(tick));
if (n == resno)
{
f = 1;
system("cls");
cout << "NAME: ";
cout << pname;
cout << "AGE: ";
cout << age;
cout << "PRESENT STATUS: ";
cout << status;
cout << "RESERVATION NUMBER: ";
cout << resno;
cout << "PRESS ANY KEY TO CONTINUE ";
system("pause");
}
}
if (f == 0)
{
system("cls");
cout << "UNRECOGINIZED RESERVATION NO !!! WANNA RETRY ? (Y / N) ";
char a;
cin >> a;
if (a == 'y' || a == 'Y')
{
system("cls");
goto X;
}
else
{
cout << "PRESS ANY KEY TO CONTINUE";
system("pause");
}
}
fn.close();
}
void ticket::reservation()
{
system("cls");
cout << "RESERVATION ";
cout << "ENTER THE BUS NO: ";
int bno, f = 0; cin >> bno; ofstream file;
ifstream fin("bus1.dat", ios::out); fin.seekg(0);
if (!fin)
{
system("cls");
cout << "ERROR IN THE FILE ";
system("cls");
while (!fin.eof())
{
fin.read((char*)&bs, sizeof(bs)); int z;
z = bs.rbusno();
if (bno == z)
{
f = 1;
noofkidsseats = bs.rnoofkidsseats();
noofwomenseats = bs.rnoofwomenseats();
noofmenseats = bs.rnoofmenseats();
noofspecialseats = bs.rnoofspecialseats();
noofvvip = bs.rnoofvvip();
}
}
if (f == 1)
{
file.open("Ticket1.dat", ios::app);
S:
system("cls");
cout << "NAME:";
cin >> pname;
cout << "AGE:";
cin >> age;
system("cls");
cout << "SELECT THE CATEGORY WHICH YOU WISH TO TRAVEL";
cout << "1.KIDS CATEGORY: ";
cout << "2.WOMEN CATEGORY: ";
cout << "3.MEN CATEGORY: ";
cout << "4.SPECIAL CATEGORY: ";
cout << "5.SECOND CLASS SLEEPER: ";
cout << "ENTER YOUR CHOICE ";
int c;
cin >> c;
switch (c)
{
case 1:
tokids++;
resno = rand();
if ((noofkidsseats - tokids)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 2:
towomen++;
resno = rand();
if ((noofwomenseats - towomen)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO:";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 3:
tomen++;
resno = rand();
if ((noofmenseats - tomen)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 4:
tospecial++;
resno = rand();
if ((noofspecialseats - tospecial)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 5:
tovvip++;
resno = rand();
if ((noofvvip - tovvip)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
}
cout << "DO YOU WISH TO CONTINUE BOOKING TICKETS (Y/N) ? ";
char n;
cin >> n;
if (n == 'y' || n == 'Y')
{
goto S;
}
}
}
if (f == 0)
{
system("cls");
cout << "ERROR IN THE BUS NUMBER ENTERED !!!";
system("pause");
}
file.close();
}
void ticket::cancellation()
{
system("cls");
ifstream fin;
fin.open("Ticket1.dat", ios::out);
ofstream file;
file.open("Temp1.dat", ios::app);
fin.seekg(0);
cout << "ENTER THE RESERVATION NO: ";
int r, f = 0;
cin >> r;
if (!fin)
{
cout << "ERROR IN THE FILE !!!";
}
while (!fin.eof())
{
fin.read((char*)&tick, sizeof(tick)); int z;
z = returnresno();
if (z != r)
{
file.write((char*)&tick, sizeof(tick));
}
if (z == r)
{
f = 1;
}
}
file.close(); fin.close();
remove("Ticket1.dat");
rename("Temp1.dat", "Ticket1.dat");
if (f == 0)
{
cout << "NO SUCH RESERVATION IS MADE !!! PLEASE RETRY ";
system("pause");
}
else
{
cout << "RESERVATION CANCELLED";
system("pause");
}
}
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "bus.h"
#include "ticket.h"
using namespace std;
int main()
{
ticket obj;
bus obj1;
int ch, r = 1000, j;
cout << "WELCOME";
Z:
cout << "BUS TICKET RESERVATION";
cout << "==========================";
cout << "1.BUS DETAILS";
cout << "2.UPDATE BUS DETAILS ";
cout << "3.RESERVING A TICKET ";
cout << "4.CANCELLING A TICKET";
cout << "5.DISPLAY THE PRESENT TICKET STATUS ";
cout << "6.EXIT";
cout << "ENTER YOUR CHOICE: ";
cin >> ch;
char n;
switch (ch)
{
case 1:
{
ifstream fin("bus1.dat", ios::out);
fin.seekg(0);
if (!fin)
{
cout << "ERROR IN THE FILE !!!";
}
else
{
while (!fin.eof())
{
fin.read((char*)&obj1, sizeof(obj1));
bs.display();
}
}
fin.close();
goto Z;
}
case 2:
{
cout << "ENTER THE PASSWORD ";
cin >> j;
cout << "CHECKING PLEASE WAIT ";
system("pause");
Y:
ofstream fout("bus1.dat", ios::app);
bs.input();
fout.write((char*)&obj1, sizeof(obj1));
fout.close();
cout << "DO YOU WISH TO CONTINUE UPDATING ?(Y/N)";
cin >> n;
if (n == 'y' || n == 'Y')
{
goto Y;
goto Z;
}
else
{
goto Z;
}
}
case 3:
{
obj.reservation();
goto Z;
}
case 4:
{
obj.cancellation();
goto Z;
}
case 5:
{
obj.print();
goto Z;
}
case 6:
{
exit(0);
}
}
system("pause");
return 0;
}
class bus
{
// members
}bs;
Not only declares a type bus but also a defines a variable bs. The same for tick.
When you include these headers in several cpp files, you get several definitions of these variables.
I'm sure none of the C++ books you have read told you to define variables like this in header files, so just don't. Declare the types in the headers and the variables where you need them, likely in the cpp files.
The instructor want us to write a program that can re displays the menu only when the user wants to restart a selection and add an option to continue with another selection.
The problem I have is when the user select a number from 1 to 4 and complete the selection, the program will ask the user if the user want to continue with another selection and when the user says no, the program still ask to select a number without ending program.
here is my code that I've written so far:
#include<iostream>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed();
int GetMinSpeed();
int GetMaxSpeed();
int CheckContinue();
int selection;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << endl;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n";
break;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
break;
}
CheckContinue();
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
CheckContinue();
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
CheckContinue();
return 0;
}
/*int SetSpeed(int sp)
{
cout << "The Set Speed is " << sp << endl;
return 0;
}
*/
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
CheckContinue();
}
int CheckContinue(void)
{
char x;
while(true)
{
cout << "\nDo you want to continue with another selection? \n"
<< "\nEnter Y or N followed by Enter: " << endl;
cin >> x;
if ( x == 'Y')
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
break;
}
}
else if(x == 'N')
{
break;
}
}
return 0;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
*/
void menu()
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int bye = 0;
while(1)
{
cout << "\nYour selection :" <<endl;
cin >> selection;
bye = 0;
if((selection <= 5)&&(selection >= 1))
{
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
else
{
cout << "\nPlease input valid selection: " << endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
if(bye == -1)
{
break;
}
}
}
int main()
{
menu();
return 0;
}//end of main function
This might serve your purpose. Call ask() as per your requirement if it didn't suit you.
#include <iostream>
#include <stdlib.h>
using namespace std;
char * title;
int a , b;
void menu();
void print(const char *c , int res )
{
cout<<"\n\n\n\n\nThe "<<c<<" of "<<a<<" and "<<b<<" is : " <<res<<endl;
}
void add()
{
print("Addition" , (a+b));
}
void sub()
{
print("subtraction" , (a-b));
}
void mul()
{
print("Multiplication" , (a*b));
}
void div()
{
print("Division" , (a/b));
}
void ask()
{
bool call_menu;
char ch;
cout<<"\n\n\n\n\n\n DO you Want to Continue? Y - N: ";
cin>>ch;
if(ch=='Y' || ch=='y')
{
call_menu= true;
}
else
{
if(ch=='N' || ch == 'n')
{
call_menu= false;
}
else
{
cin.clear();
ask();
}
}
if(call_menu)
{
system("clear"); // change this to system("cls") if on windows
menu();
}
else
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\n\n\n\n\t\t\tHave a Nice Day ! \n\n\n"<<endl;
}
}
void input(int *first , int *second)
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"Enter the First Number : ";
cin>>(*first);
cout<<"\nEnter the Second Number :";
cin>>(*second);
}
void menu()
{
int ch;
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"\n\n\t\t\t1 . Addition"<<endl;
cout<<"\n\n\t\t\t2 . Subtract"<<endl;
cout<<"\n\n\t\t\t3 . Multiply"<<endl;
cout<<"\n\n\t\t\t4 . Division"<<endl;
cout<<"\n\n\t\t\t5 . Exit" <<endl;
cout<<"\n\n\n\n Enter Your Choice : ";
cin>>ch;
if(ch >=1 && ch <5){
input(&a , &b);
}
switch(ch)
{
case 1:
add();
ask();
break;
case 2:
sub();
ask();
break;
case 3:
mul();
ask();
break;
case 4:
div();
ask();
break;
case 5:
exit(0);
break;
default:
system("clear"); // change this to system("cls") if on windows
cin.clear();
cin.ignore();
menu();
break;
}
}
int main(int argc, char **argv)
{
menu();
return 0;
}
Modify it as per your requirement.
There are several problems with the code in your question. The big problem is there is a lot of redundant code that can be easily eliminated by a few minor adjustments. You have both the menu printing and code to act on selections in several places. This is going to make managing the continue process a lot more difficult. By eliminating the redundant code and adjusting the logic in main and and menu you can not only reduce the complexity but make it far easier to manage.
For instance menu can be changed to remove the while loop and return a boolean value to indicate if the user wants to exit. This will allow you to select an option, act on it, then return letting other portions of the program handle asking the user if they want to continue.
The example below is a modification of your original code. It only addresses the logic for asking the user to continue and eliminates the redundant menu code. You should review the entire code and make additional adjustments as necessary.
#include <iostream>
#include <string>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << flush;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n" << flush;
continue;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
return speed;
}
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
return 0;
}
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
returns false if the user has selected the exit option
returns true for all other options
*/
bool menu()
{
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int selection;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
return false;
break;
default:
cout << "\nPlease input valid selection: " << endl;
}
return true;
}
int main()
{
for(bool process = true; process;)
{
process = menu();
if(process)
{
for(bool valid = false; !valid;)
{
cout << "\nDo you want to enter another selection? (Yes/No) " << flush;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string line;
getline(cin, line);
if(line == "No")
{
valid = true;
process = false;
}
else if(line == "Yes")
{
valid = true;
}
else
{
cout << "\nInvalid input\n\n" << flush;
}
}
}
}
return 0;
}//end of main function