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
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;
}
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;
I am creating a program to modify the records in a binary file. But i always end up creating two similar records.
I copy all the data to another file. if I find the record to be modified, I read the modified data and copy it to the new file. When all the records are copied, The remporary file is renamed
The class:
class student
{
char name[200];
int rno;
float marks;
char grad;
void grade()
{
if(marks < 33)
grad = 'F';
else if(marks < 50)
grad = 'D';
else if(marks < 60)
grad = 'C';
else if(marks < 80)
grad = 'B';
else
grad = 'A';
}
public:
void get()
{
fflush(stdin);
cout << "Name: ";
gets(name);
cout << "Roll number: ";
cin >> rno;
cout << "Marks:" ;
cin >> marks;
grade();
}
///////////////////////////////////////////////////////////
void showname()
{
cout << "Name: " << name << endl;
}
///////////////////////////////////////////////////////////
void show()
{
cout << "Name: " << name << endl;
cout << "Roll number: " << rno << endl;
cout << "Marks: " << marks << endl;
cout << "Grade: " << grad << endl;
}
///////////////////////////////////////////////////////////
int get_rno()
{
return rno;
}
////////////////////////////////////////////////////////////
float get_marks()
{
return marks;
}
////////////////////////////////////////////////////////////
char get_grade()
{
return grad;
}
////////////////////////////////////////////////////////////
char* getname()
{
return name;
}
};
The modify function:
void modify_rec()
{
int rno;
ifstream fin("stu.dat",ios::binary);
ofstream fout("modif.dat",ios::binary);
student s;
cout << "Enter the roll number whose details you want to edit:";
cin >> rno;
while(!fin.eof())
{
if(fin.eof())
break;
fin.read((char*)&s, sizeof(s));
if(s.get_rno() == rno)
{
s.get();
fout.write((char*)&s, sizeof(s));
rno = -1;
}
else
{
fout.write((char*)&s, sizeof(s));
}
}
fin.close();
fout.close();
remove("stu.dat");
rename("modif.dat","stu.dat");
}
Main function:
int main()
{
char op;
int ch;
do
{
system("CLS");
cout << "Select an option:" << endl;
cout << "\t1.)Add record." << endl;
cout << "\t2.)Display all." << endl;
cout << "\t3.)Search by roll number." << endl;
cout << "\t4.)Search by name" << endl;
cout << "\t5.)Modify record." << endl;
cout << "\t6.)Delete record." << endl;
cout << "\t7.)Display list of distinction holders." << endl;
cout << "\t8.)Create list of failures." << endl;
cout << "\t9.)Display report card." << endl;
cin >> ch;
switch(ch)
{
case 1: add_rec(); break;
case 2: disp_all(); break;
case 3: search_rno(); break;
case 4: search_name(); break;
case 5: modify_rec(); break;
case 6: delete_rec(); break;
case 7: disp_distinction(); break;
case 8: create_failure(); break;
case 9: disp_repcrd(); break;
}
cout << "Do you want to continue?" << endl;
cin >> op;
}while(tolower(op) == 'y');
}
I'm trying to make a choice list in a program and now I'm stuck with what happens when user writes incorrect input.
I've tried doing it with do loop (I've looped switch statement). Also, tried to set variable key to integer and char, but both have problems. Char only takes one character and when you write more than one it starts checking every by itself. Using int I get an infinite loop of menu function when inputting incorrectly.
Also, tried using cin.fail(), which I've found here, in stackoverflow, but it didn't work out.
void menu()
{
if(!isEmpty())
{
showStack();
}
else
{
cout << "stekas tuscias!" << endl;
}
cout << "---------------------------" << endl;
cout << "1. Iterpti i steka (push)" << endl;
cout << "2. Pasalinti is steko (pop)" << endl;
cout << "3. Issaugoti steka" << endl;
cout << "4. Issaugoti steka ir uzdaryti programa" << endl;
cout << "---------------------------" << endl;
cout << "Jusu pasirinkimas: ";
char key;
cin >> key;
switch(key)
{
case '1':
{
cout << "Irasykite reiksme i konsole: ";
int data;
cin >> data;
cout << endl;
push(data);
break;
}
case '2':
{
cout << endl;
pop();
break;
}
case '3':
{
write();
cout << "--------" << endl;
cout << "Stekas issaugotas!" << endl;
cout << "--------" << endl;
menu();
break;
}
case '4':
{
write();
break;
}
default:
{
cout << "Tokio pasirinkimo nera!" << endl;
cout << endl;
key = '\0';
menu();
break;
}
}
}
My whole code if it's needed: https://pastebin.com/Xv1HE0Mh
Use a try-catch-throw block. Use decltype or typeof feature to see if the input is an integer.
I'm sure why cin.fail() or (!cin) isn't working for you. But, you can do this. And, I'm also sure this kind of question exists.
template <class T>
int check (T ch)
{
if (ch >= 'a' && ch <= 'Z') return 0;
else return 1;
}
And, then.
main ()
{
.
.
char c;
cin.get (c); //Note here!!
if (check (c)) {...}
else {...} //You can use goto.
.
}
Hey guys I'm trying to work out how to call a function in my code using a switch statement. I have tried to look for many different references but no matter what nothing seems to work if somebody could please put me on the right path that would be a big help. Here's the code:
#include <iostream>
#include <string>
using namespace std;
int playGame(string word);
int main()
{
int choice;
bool menu = true;
do{
cout <<"Please select one of the following options: \n";
cout << "1: Play\n"
"2: Help\n"
"3: Config\n"
"4: Quit\n";
cout << "Enter your selection (1, 2 and 3): ";
cin >> choice;
//*****************************************************************************
// Switch menu to display the menu.
//*****************************************************************************
switch (choice)
{
case 1:
cout << "You have chosen play\n";
int playGame(string word);
break;
case 2:
cout << "You have chosen help\n";
cout << "Here is a description of the game Hangman and how it is played:\nThe word to guess is represented by a row of dashes, giving the number of letters, numbers and category. If the guessing player suggests a letter or number which occurs in the word, the other player writes it in all its correct positions";
break;
case 3:
cout << "You have chosen Quit, Goodbye.";
break;
default:
cout<< "Your selection must be between 1 and 3!\n";
}
}while(choice!=3);
getchar();
getchar();
cout << "You missed " << playGame("programming");
cout << " times to guess the word programming." << endl;
}
int playGame(string word) //returns # of misses
{
//keep track of misses
//guess is incorrect
//repeated guess of same character
//guess is correct
int misses = 0;
int exposed = 0;
string display = word;
for(int i=0; i< display.length(); i++)
display[i] ='*';
while(exposed < word.length()) {
cout << "Miss:" << misses << ":";
cout << "Enter a letter in word ";
cout << display << " : ";
char response;
cin >> response;
bool goodGuess = false;
bool duplicate = false;
for(int i=0 ; i<word.length() ; i++)
if (response == word[i])
if (display[i] == word[i]) {
cout << response << " is already in the word.\n";
duplicate = true;
break;
} else {
display[i] = word[i];
exposed++;
goodGuess = true;
}
if (duplicate)
continue;
if (!goodGuess){
misses ++;
cout << response << " is not in the word.\n";
}
}
cout << "Yes, word was " << word << "." << endl;
return misses;
}
You are not calling playGame function in switch statement,
switch (choice)
{
case 1:
cout << "You have chosen play\n";
//int playGame(string word); // this does not call playGame,
// it re-declare playGame function again
playGame("word"); // this will call playGame with word parameter
//^^^^^^^^^^^^^^^
break;
int playGame(string word);
In your switch statement might be the problem...try:
int misses = playGame(word);
You are trying to return the number of misses from your playGame method so you have to put the return data inside a variable.