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();
}
Related
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;
}
I am trying to code exception handling in my switch statement for a memnu in case user inputs something other than an int. Tried many different methods and still get continuous loop when user inputs a character.
I have tried using std exception but even with the include my compiler still sees error during build.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;
class Exam
{
public:
int loadExam()
{
//ifstream infile;
//string examName = exam;
ifstream infile("exam.txt");
streambuf *cinbuf = cin.rdbuf(); //save old buf
cin.rdbuf(infile.rdbuf()); //redirect std::cin to infile.txt!
string line, theQuestion, questiontype, theAnswer;
int questionvalue;
//get the number of questions from the first line in the file
getline(cin,line);
numquestions = atoi(line.c_str());
for(int count = 0; count < numquestions; count++){
getline(cin,line);
//get the next line with the question type and the value of the question
int npos = line.size();
int prev_pos = 0;
int pos = 0;
while(line[pos]!=' ')
pos++;
questiontype = line.substr(prev_pos, pos-prev_pos);
prev_pos = ++pos;
questionvalue = atoi(line.substr(prev_pos, npos-prev_pos).c_str()); // Last word
//process a true/false question
if (questiontype == "TF")
{
myQuestions[count] = new QuestionTF;
getline(cin,theQuestion);
myQuestions[count]->setQuestion(theQuestion,questionvalue);
}
//process a multiple choice question
if (questiontype == "MC")
{
myQuestions[count] = new QuestionMC;
getline(cin,theQuestion);
myQuestions[count]->setQuestion(theQuestion,questionvalue);
}
}
cin.rdbuf(cinbuf); //restore cin to standard input
return numquestions;
}
void displayExamQuestions(int numquestions)
{
string qtype;
//print out the questions that have been processed
for(int count = 0; count<numquestions;count++)
{
qtype = myQuestions[count]->getQuestionType();
cout << qtype << " " << myQuestions[count]->getValue() << "\n";
myQuestions[count]->printOptions();
cout << "\n";
}
}
private:
Question *myQuestions[10];
int numquestions;
};
int main() {
Exam myExam;
int numquestions;
int choice;
while((choice = displayMenu())!=3)
switch(choice)
{
case 1:
numquestions = myExam.loadExam();
break;
case 2:
myExam.displayExamQuestions(numquestions);
break;
default:
cout << "Invalid choice. Try again.\n\n";
}
getchar();
return 0;
}
int displayMenu()
{
int choice;
cout << "\t===================== Exam Menu =====================" << endl;
cout << "\t1. Load Exam "<<endl;
cout << "\t2. Display Exam "<<endl;
cout << "\t3. Quit"<<endl;
cout << "\t=====================================================" << "\n" << endl;
cout << "Please enter your selection: ";
cin >> choice;
cout << "\n" << endl;
return choice;
}
Require output to read "Invalid selection, Please try again" when a user inputs a character or string of alpha characters.
In this case, validation should be handled by the displayMenu function for two reasons.
The displayMenu function says that it will return an integer so it should be responsible for ensuring the user inputs a number, not a char or string.
The displayMenu lists the options so it knows how many options are available, meaning it should also check that the integer is between 1 and 3.
Infinite loop with cin when typing string while a number is expected
int displayMenu() //This function should be responsible for validating that an
// int was inputed
{
int choice;
while (true)
{
cout << "\t===================== Exam Menu =====================" << endl;
cout << "\t1. Load Exam " << endl;
cout << "\t2. Display Exam " << endl;
cout << "\t3. Quit" << endl;
cout << "\t=====================================================" << "\n" << endl;
cout << "Please enter your selection: ";
cin >> choice;
cout << "\n" << endl;
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //This clears out the stream if they entered a string
//Try using cin.ignore() and inputing a string to see what happens.
}
else if (choice >= 1 && choice <= 3)
{
break;
}
}
return choice;
}
You could decouple this second part by having a displayMenu function that simply prints the menu and a second function called getInput that doesn't care what integer is inputed. It would then be up to the calling function to make sure the value is between 1 and 3.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;
void displayMenu();
int getInput();
int main() {
int numquestions;
int choice = 0;
while (choice != 3)
{
displayMenu();
while ((choice = getInput()) < 1 || choice > 3)
{
std::cout << "Please pick a value between 1 and 3\n";
displayMenu();
}
switch (choice)
{
case 1:
cout << "Case 1\n";
break;
case 2:
cout << "Case 2\n";
break;
default:
cout << "Invalid choice. Try again.\n\n";
}
}
getchar();
return 0;
}
//Only responsible for getting an int
int getInput()
{
int choice;
while (true)
{
cin >> choice;
cout << "\n" << endl;
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::cout << "Please enter a valid number\n";
}
else
{
break;
}
}
return choice;
}
//This function only displays a menu
void displayMenu()
{
cout << "\t===================== Exam Menu =====================" << endl;
cout << "\t1. Load Exam " << endl;
cout << "\t2. Display Exam " << endl;
cout << "\t3. Quit" << endl;
cout << "\t=====================================================" << "\n" << endl;
cout << "Please enter your selection: ";
}
Im new at programming and for homework, my teacher ask me to make an option menu that does different things, but I have a problem, case 5 is supposed to end the program, but if I select 5, the do-while cycle keeps asking me if I want to do something else, when I need that if I choose 5, the program ends, how can I end with the cycle and put the option to exit the program?
Thanks, and any help is welcome
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
using namespace std;
int main() {
string name, lname;
int an, result;
int num;
char option;
int n, x;
time_t t, b;
char* f;
int flag = 0;
int i = 0;
do {
cout << "Option Menu";
cout << "\n1) Name and your last name";
cout << "\n2) Years of life";
cout << "\n3) First 100 numbers divisible by 3";
cout << "\n4) Date and hour";
cout << "\n5) Exit\n";
cin >> num;
switch (num) {
case 1:
cout << "\nWrite your name: ";
cin >> name;
cout << "\nWrite your last name: ";
cin >> lname;
cout << "\nYour complete name is: " << name << " " << lname;
break;
case 2:
cout << "\nWhat year you were born?: ";
cin >> an;
result = 2019 - an;
cout << "\nYou have " << result << " years\n";
break;
case 3:
for (i = 0; flag < 100; i++) {
if (i % 3 == 0) {
cout << i << "\n";
flag++;
}
}
break;
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
}
cout << "\n Do you want to do something else?: ";
cin >> option;
} while (option == 's' or option == 'S');
cout << "\nGood bye :)" << endl;
system("pause");
return 0;
}
It's probably easiest to just simply use the if statement to check if num == 5 outside the switch statement and break the while loop when num is equal to 5.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
using namespace std;
int main() {
string name, lname;
int an, result;
int num;
char option;
int n, x;
time_t t, b;
char* f;
int flag = 0;
int i = 0;
do {
cout << "Option Menu";
cout << "\n1) Name and your last name";
cout << "\n2) Years of life";
cout << "\n3) First 100 numbers divisible by 3";
cout << "\n4) Date and hour";
cout << "\n5) Exit\n";
cin >> num;
switch (num) {
case 1:
cout << "\nWrite your name: ";
cin >> name;
cout << "\nWrite your last name: ";
cin >> lname;
cout << "\nYour complete name is: " << name << " " << lname;
break;
case 2:
cout << "\nWhat year you were born?: ";
cin >> an;
result = 2019 - an;
cout << "\nYou have " << result << " years\n";
break;
case 3:
for (i = 0; flag < 100; i++) {
if (i % 3 == 0) {
cout << i << "\n";
flag++;
}
}
break;
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
}
if (num == 5) {
break;
}
cout << "\n Do you want to do something else?: ";
cin >> option;
} while (option == 's' || option == 'S');
cout << "\nGood bye :)" << endl;
system("pause");
return 0;
}
To accomplish this task, your switch must have either a case 5: or a default: block which assigns a value other than s or S to the option variable. That will allow your program to break out of the do..while loop.
There is another problem though. The user will still be asked if he wants to do something else even if they chose the Exit option. To avoid this, you can use an extra variable (for example, a userExits boolean) to skip the part where the program asks for input after the switch.
Here is a possible solution:
// after all the variable declarations
bool userExits = false;
do {
// All menu options
cin >> num;
switch (num) {
// (...)
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
case 5:
userExits = true;
break;
}
if (userExits){
option = "exit";
}
else{
cout << "\n Do you want to do something else?: ";
cin >> option;
}
} while (option == 's' or option == 'S');
cout << "\nGood bye :)" << endl;
In the adding user section in the code below, I am unable to type any characters for the "Add another person?(y/n): " question. it just jumps back to entering age. How do I fix this?
I've tried to change ans into a string, implement a while loop to force the question to show up, and many other things. It just seems that nothing works and I've been trying it for the good part of two hours
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
char ans;
int people;
int option;
int count = 0;
struct data
{
string name;
int age;
char gender;
string comments;
}person[100];
// homescreen
homescreen:
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for (int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
// using options
while (option != 5)
{
if (option == 1)
{
view:
for (int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[count].name << endl;
cout << "Age: " << person[count].age << endl;
cout << "Gender: " << person[count].gender << endl;
cout << "Comments: " << person[count].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls"); goto view;
}
else if (ans == 'n')
{
system("cls"); goto homescreen;
}
}
if (option == 2)
{
add:
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls");
goto add;
}
else if (ans == 'n')
{
system("cls");
goto homescreen;
}
}
}
}
If you anybody can help me I'd be grateful
The goto statements in your code makes the program really good
spaghetti
structure and that is not
good.
Therefore, think instead of goto other options, such as infinite
while loop which will break once the user enters the n or moving
the code to the function.
Secondly what if you have not entered any persons and choosing the
option 1. You still output the attributes of the person as
count is initialized zero at least. Remember the attributes are
not initialized at this point. Accessing the uninitialized
variables will invoke undefined
behavior. Therefore,
provide a check (something like if(count > 0) )before you execute the code in option 1.
In addition to that, remember that
std::endl flushes the output buffer, and '\n' doesn't. Therefore, most of
the cases you might wanna use just
\n.
Last but not the least, use std::vector instead of the using C style arrays with some predefined size. What if the user has more than 100 inputs? The solution in C++ is std::vector, which can expand dynamically as its storage is handled automatically.
Following is a possible solution to your program, in which the comments will guide you through to the things that I mentioned above.
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
struct Data
{
std::string name;
int age;
char gender;
std::string comments;
Data(const std::string& n, int a, char g, const std::string& c) // provide a Constructor
:name(n), age(a), gender(g), comments(c)
{}
};
void debugMsg(const std::string& msg)
{
system("cls");
std::cout << "\n\n\t\t" << msg << "\n\n";
Sleep(3000);
}
int main()
{
std::vector<Data> person; // use std::vector to store the datas
while (true) // loop: 1
{
system("cls");
std::cout << "Welcome to the Data Base! \n\n";
std::cout << "[1] View Person\n";
std::cout << "[2] Add Person\n";
std::cout << "[3] Edit Person\n";
std::cout << "[4] Delete Person\n";
std::cout << "[5] Exit\n";
std::cout << "Choose Option: ";
int option; std::cin >> option;
switch (option) // use switch to validate the options
{
case 1:
{
while (true) // loop - 2 -> case 1
{
// if no data available to show -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (person.empty()) { debugMsg("No person available to show ....going to main manu...."); break; }
// otherwise: displaying all people
for (std::size_t index = 0; index < person.size(); ++index)
std::cout << index << ".) " << person[index].name << "\n";
std::cout << "\nEnter number of person you want: ";
std::size_t index; std::cin >> index;
// if the index is not valid -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (index < 0 || index >= person.size()) { debugMsg("Sorry, wrong index!... returning to the main menu......"); break; }
system("cls");
std::cout << "Name: " << person[index].name << std::endl;
std::cout << "Age: " << person[index].age << std::endl;
std::cout << "Gender: " << person[index].gender << std::endl;
std::cout << "Comments: " << person[index].comments << std::endl << std::endl;
std::cout << "View another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; } // just continue looping
else if (ans == 'n') { break; } // this will break the loop 2 and return to the outer loop(i.e, loop 1)
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 2:
{
while (true) // loop - 3 -> case 2
{
system("cls");
std::string name, comments; int age; char gender;
std::cout << "Name: "; std::cin >> name;
std::cout << "Age: "; std::cin >> age;
std::cout << "Gender(M/F/H): "; std::cin >> gender;
std::cout << "Comments: "; std::cin >> comments;
// simply construct the Data in person vector in place
person.emplace_back(name, age, gender, comments);
std::cout << "\n\nAdd another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; }
else if (ans == 'n') { system("cls"); break; } // same as case 1
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 3: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 4: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 5: return 0; // if its 5, just retun the main
default: break;
}
}
return 0;
}
As mentioned above, using "goto" is a bad style, so i would suggest structure your program a little. Below is my version.
Naturally, I did not add any checks and controls, the author will be able to do this on his own. But main logics should work. And, of course, it is better to use vector instead of static array.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
enum options { OPT_VIEW = 1, OPT_ADD = 2, OPT_EDIT = 3, OPT_DELETE = 4, OPT_EXIT = 5 };
struct data
{
string name;
int age;
char gender;
string comments;
};
class App
{
private:
data person[100];
int count = 0;
public:
App();
void Run();
int HomeScreen();
void View();
void Add();
};
App::App() : count(0)
{}
void App::Run()
{
int option = HomeScreen();
while(option != OPT_EXIT)
{
switch(option)
{
case OPT_VIEW:
View();
break;
case OPT_ADD:
Add();
break;
}
option = HomeScreen();
}
}
int App::HomeScreen()
{
int option = 0;
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for(int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
return option;
}
void App::View()
{
char ans = 0;
do
{
int people = 0;
for(int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[people].name << endl;
cout << "Age: " << person[people].age << endl;
cout << "Gender: " << person[people].gender << endl;
cout << "Comments: " << person[people].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
void App::Add()
{
char ans = 0;
do
{
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
int main()
{
App program;
program.Run();
}
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.