Program won't read the inputted name to edit other info - c++

When I input the info needed in addstudent(), it works. But when I try to edit the info, using the name I input to search for the info to edit, it doesn't work.
Here is the sample:
#include<iostream>
#include<cstring>
#include<cctype>
#include<vector>
using namespace std;
struct studmem{
char name[50];
int age;
char course[50];
int yrlvl;
char spcl[50];
}s[10];
void addstudent(studmem s[],int lngth, int &val){
for (int i = 0; i < lngth; i += 1) {
int CheckCharacter = 0;
int counter = 0;
int CheckCharacters = 0;
do{
int chkchr=1;
cout<<"Enter name: ";
cin.getline(s[val].name,50);
for(int i=0;i<strlen(s[val].name);i++){
if(!(isalpha(s[val].name[i])||isspace(s[val].name[i]))){
cout<<"Invalit input! Please try again!\n";
chkchr=0;
break;
}
}
if(chkchr==1){
break;
}
}while(1);
cout << "Enter your age: ";
cin >> s[val].age;
cin.ignore();
while (s[val].age >= 35 || s[val].age <= 17) {
cout << "Invalid age. Please enter your age again: ";
cin >> s[val].age;
}
while (CheckCharacter == 0) {
cout << "Enter Course: ";
cin.getline(s[val].course, 30);
if (strcmp(s[val].course, "BSIT") == 0)
{
CheckCharacter++;
}
else if (strcmp(s[val].course, "BSCS") == 0) {
CheckCharacter++;
}
else {
cout << "Invalid Input! Please try again!" << endl;
}
}
do{
CheckCharacter = 0;
cout << "Enter Year Level: ";
cin >> s[val].yrlvl;
if (s[val].yrlvl >= 1 && s[val].yrlvl <= 4){
CheckCharacter++;
}
else {
cout << "Invalid Input. Please Enter Year Level Again!\n";
}
}while (CheckCharacter == 0);
CheckCharacter = 0;
cin.ignore();
while (CheckCharacter == 0) {
cout << "Enter Specialization: ";
cin.getline(s[val].spcl, 50);
if (strcmp(s[val].course, "BSIT") == 0)
{
if (strcmp(s[val].spcl, "AGD") == 0)
CheckCharacter++;
else if (strcmp(s[val].spcl, "DA") == 0)
CheckCharacter++;
else if (strcmp(s[val].spcl, "WMA") == 0)
CheckCharacter++;
else if (strcmp(s[val].spcl, "SMBA") == 0)
CheckCharacter++;
else
{
cout << "Invalid Input. Please Enter Specialization Again";
}
}
else if (strcmp(s[val].course, "BSCS") == 0) {
if (strcmp(s[val].spcl, "SE") == 0)
CheckCharacter++;
else if (strcmp(s[val].spcl, "DS") == 0)
CheckCharacter++;
else
{
cout << "Invalid Input. Please Enter Specialization Again";
}
}
else {
cout << "Invalid Input. Please Enter Specialization Again(For BSIT: WMA, DA, AGD, SMBA For BSCS: DS, SE)";
}
}
val += 1;
}
}
void edstudent(studmem s[]){
int CheckCharacter=0;
do{
char studname[50];
cout<<"Search Name of Student: ";
cin.ignore();
cin.getline(studname,50);
for(int i=0;i<strlen(s[i].name);i++){
if((strcmp(studname,s[i].name))==0){
CheckCharacter++;
}
else{
cout<<"Student not found, please try again!\n";
break;
}
}
}while(CheckCharacter=0);
}
int main(){
bool Code = 1;
int rec=0;
int list = 0;
int value = 0;
do {
int ch;
cout << "Student Record" << endl;
cout << "1) Add" << endl;
cout << "2) View" << endl;
cout << "3) Edit" << endl;
cout << "4) Exit" << endl;
cout << "Maximum of 10 Students" << endl;
cout << "No. of Students: " << rec << endl;
cout << "\nChoice: ";
cin >> ch;
cin.ignore();
switch (ch) {
case 1: {
rec += 1;
addstudent(s, 1, value);
break;
}
case 2:{
for(int i=0;i<rec;i++){
cout<<"Student #"<<i+1;
cout<<"\nName: "<<s[i].name<<endl;
cout<<"Age: "<<s[i].age<<endl;
cout<<"Course: "<<s[i].course<<endl;
cout<<"Year Level: "<<s[i].yrlvl<<endl;
cout<<"Specialization: "<<s[i].spcl<<endl;
cout<<endl;
}
break;
}
case 3:{
edstudent(s);
break;
}
default:
cout<<"Invalid Input! Please try again!\n";
main();
}
} while (1);
}
I tried changing (int i=0;i<strlen(s[i].name);i++) because they say it's the problem, but it just doesn't work.
The main problem is here, I think:
void edstudent(studmem s[]){
int CheckCharacter=0;
do{
char studname[50];
cout<<"Search Name of Student: ";
cin.ignore();
cin.getline(studname,50);
for(int i=0;i<strlen(s[i].name);i++){
if((strcmp(studname,s[i].name))==0){
CheckCharacter++;
}
else{
cout<<"Student not found, please try again!\n";
break;
}
}
}while(CheckCharacter=0);
}
Hoping you can help me, since I'm new to C++.

Related

Class not storing Vector values

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 getting the linking errors in my C++ program, I could not compile my code

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.

Taking player input

I need help on how to allowing player to input a number in this code:
using namespace std;
int main()
{
char name[50];
menu:
cout << "Select your choice..." << endl;
cout << "1) Start Game" << endl;
cout << "2) Help" << endl;
cout << "3) Exit Game" << endl;
cin.getline(number, 1);
if(number = 1) {
start_game();
}
else if(number = 2){
help();
}
else if(number = 3){
exit();
}
else {
goto menu;
}
return 0;
}
It says that there is a problem in the cin.getline(number,1) in my program. If anyone knows how to fix it, please tell me. Thanks
Do it like this:
using namespace std;
int main()
{
char name[50];
while (true) // Use a loop instead of goto since it is more readable for other developers
{
cout << "Select your choice..." << endl;
cout << "1) Start Game" << endl;
cout << "2) Help" << endl;
cout << "3) Exit Game" << endl;
int number; // You didn't declare `number`
cin >> number; // You used getline wrong
if (number == 1) { // Use `==` for comparing
start_game();
break;
}
if (number == 2) {
help();
break;
}
if (number == 3) {
exit();
break;
}
}
return 0;
}
I explained some fixes in the comments.
#include <iostream>
using namespace std;
int main()
{
char name[50];
int number ;
menu:
cout << "Select your choice..." << endl;
cout << "1) Start Game" << endl;
cout << "2) Help" << endl;
cout << "3) Exit Game" << endl;
cin >> number;
if(number == 1) {
start_game();
}
else if(number == 2){
help();
}
else if(number == 3){
exit();
}
else {
goto menu;
}
return 0;
}

C++ can't update one of my variables

I had this school assignment to build an atm machine. I got it to work but if I deposit or withdrawal money and view my account balance later its still not updated. Can someone tell me what I am doing wrong and any suggestion on how to make my code better, in general, would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void WelcomeMenu();
void Menu();
void userChoiceDeposite(double accountbalance);
void userChoiceWithdraw(double accountbalance);
void userChoiceView(double accountbalance);
void printReceipt();
int main ()
{
//clear receipt.txt from previous transactions
ofstream clearFile("Receipt.txt");
clearFile.close();
//Declaring variables
string userInput;
char userAction;
//prompt user for input, start the program or quit
cout <<"Enter start to continue, or Q/q to quit ";
getline (cin, userInput);
cout <<endl;
//check the input
if ((userInput == "q") || (userInput == "Q"))
{
cout <<"Have a nice day!" <<endl;
return 0;
}
else if (userInput == "start")
{
const int sizeLimit = 50;
string firstName[sizeLimit], lastName[sizeLimit], passWord[sizeLimit];
double accountBalance[sizeLimit];
int count = 0;
ifstream readFile("Accounts.txt");
while (!readFile.eof())
{
readFile >> firstName[count];
readFile >> lastName[count];
readFile >> passWord[count];
readFile >> accountBalance[count];
count++;
}
//ask for username/pw
string fName, lName, pwd;
double accountbalance;
bool exists = false;
do
{
cout <<"Enter First Name: ";
cin >> fName;
cout <<"Enter Last Name: ";
cin >>lName;
cout <<"Enter Password: ";
cin >> pwd;
for (int i=0; i<sizeLimit; i++)
{
if (firstName[i] == fName)
{
if (lastName[i] == lName)
{
if (passWord[i] == pwd)
{
exists = true;
accountbalance = accountBalance[i];
}
}
}
}
}
while (exists == false);
//if correct display menu
WelcomeMenu();
cin >> userAction;
//while login is valid (true)
while (userAction != 'q')
{
if (userAction == 'D' || userAction == 'd')
{
userChoiceDeposite(accountbalance);
}
else if (userAction == 'W' || userAction == 'w')
{
userChoiceWithdraw(accountbalance);
}
else if (userAction == 'V' || userAction == 'v')
{
userChoiceView(accountbalance);
}
else if (userAction == 'P' || userAction == 'p')
{
printReceipt();
return 0;
}
else
{
cout <<"Have a nice Day" <<endl;
return 0;
}
Menu();
cin >> userAction;
}
}
else
{
cout <<"Input Error..." <<endl;
}
return 0;
}
//welcome menu display function
void WelcomeMenu()
{
cout <<"Welcome to your account " <<endl;
cout <<endl;
cout <<"[D/d] Deposit Money" <<endl;
cout <<"[W/w] Withdraw Money" <<endl;
cout <<"[V/v] View Account Balance" <<endl;
cout <<"[Q/q] Quit" <<endl;
}
//function after action was taken (add print option)
void Menu()
{
cout <<endl;
cout <<"[D/d] Deposit Money" <<endl;
cout <<"[W/w] Withdraw Money" <<endl;
cout <<"[V/v] View Account Balance" <<endl;
cout <<"[P/p] Print Receipt and quit" <<endl;
cout <<"[Q/q] Quit" <<endl;
}
//deposit function
void userChoiceDeposite(double accountbalance)
{
int depositMoney;
cout <<"Enter the ammount of money you want to deposit. Max $10000" <<endl;
cin >> depositMoney;
if ((depositMoney > 0) && (depositMoney <= 10000))
{
accountbalance = accountbalance + depositMoney;
ofstream saveAction("Receipt.txt", ios_base::app);
saveAction << "You made a deposit of $" <<depositMoney <<endl;
saveAction.close();
}
else
{
cout <<"Incorrect ammount" <<endl;
return userChoiceDeposite(1);
}
}
//withdraw function
void userChoiceWithdraw(double accountbalance)
{
int withdrawMoney;
cout <<"Enter the ammount of $ you want to withdraw:";
cin >> withdrawMoney;
if (accountbalance < withdrawMoney)
{
cout <<"You dont have that much money"<<endl;
return userChoiceWithdraw(1);
}
else
{
accountbalance = accountbalance - withdrawMoney;
ofstream saveAction("Receipt.txt", ios_base::app);
saveAction << "You withdrew $" <<withdrawMoney <<endl;
saveAction.close();
}
}
//view function
void userChoiceView(double accountbalance)
{
cout <<"Your account balance is $" <<accountbalance <<endl;
ofstream saveAction("Receipt.txt", ios_base::app);
saveAction << "You viewed your account balance" <<endl;
saveAction.close();
}
//print receipt function
void printReceipt()
{
ofstream saveAction("Receipt.txt", ios_base::app);
saveAction << "" <<endl;
saveAction << "" <<endl;
saveAction << "" <<endl;
saveAction << "Thank you! Come again!" <<endl;
saveAction.close();
}
You are only changing the value that you pass into the function (thus not changing the accountbalance outside of the function). For your methods where you need to update the accountbalance you either need to:
Pass by reference
Create a global variable
use a return value to update the account balance
Try one of these and see how it goes.

Menu driven project

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