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.
.
}
Related
I am a beginner and still learning how to use a switch statement. My professor asked us to make a linked list using a switch statement. I don't really know why the switch statement is not working as intended to be. Hoping someone can help me.
OUTPUT
The output of the program should look like this
Menu
[1] Inserting value in the link
[2] Deleting value in the link
[3] Exit
Enter your choice: (Input)
Inserting/Deleting a value at
[a] Beginning
[b] Middle
[c] End
[d] Exit
Enter your choice: (Input)
Input the value to be inserted/deleted: (Input)
The values in the link are: (Output)
CODE
Here is the code that I'm working with
#include <iostream>
#include <malloc.h>
#include <conio.h>
#define getch() _getch()
using namespace std;
struct dlinklist
{
struct dlinklist* left;
int data;
struct dlinklist* right;
};
typedef struct dlinklist node;
node* start = NULL;
node* getnode()
{
node* newnode;
newnode = (node*)malloc(sizeof(node));
cout << "\n Input the value to be inserted: ";
cin >> newnode->data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
int menu()
{
char ah;
int ch;
cout << "\n----------------------------------";
cout << "\nMenu";
cout << "\n----------------------------------";
cout << "\n[1] Inserting value in the link";
cout << "\n[2] Deleting value in the link";
cout << "\n[3] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ch;
if (ch == 1)
{
cout << "\n----------------------------------";
cout << "\n Inserting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
}
else if (ch == 2)
{
cout << "\n----------------------------------";
cout << "\n Deleting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
}
else if (ch == 3)
{
exit(0);
}
}
void insert_beg()
{
//code
}
void insert_end()
{
//code
}
void insert_mid()
{
//code
}
void delete_beg()
{
//code
}
void delete_end()
{
//code
}
void delete_mid()
{
//code
}
void main(void)
{
int ch = menu();
char ah;
while(1)
{
ah = menu();
switch(ah)
{
case 'A': case 'a':
if (ch == 1)
{
insert_beg();
break;
}
else
{
delete_beg();
break;
}
case 'B': case 'b':
if (ch == 1)
{
insert_mid();
break;
}
else
{
delete_mid();
break;
}
case 'C': case 'c':
if (ch == 1)
{
insert_end();
break;
}
else
{
delete_end();
break;
}
case 'D': case 'd':
exit(0);
}
}
return;
}
menu does not return any value.
You probably want to do this:
int menu()
{
char ah;
int ch;
cout << "\n----------------------------------";
cout << "\nMenu";
cout << "\n----------------------------------";
cout << "\n[1] Inserting value in the link";
cout << "\n[2] Deleting value in the link";
cout << "\n[3] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ch;
if (ch == 1)
{
cout << "\n----------------------------------";
cout << "\n Inserting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
return ah; // return statement
}
else if (ch == 2)
{
cout << "\n----------------------------------";
cout << "\n Deleting a value at:";
cout << "\n[a] The Beginning of the list";
cout << "\n[b] The middle of the list";
cout << "\n[c] The end of the list";
cout << "\n[d] Exit";
cout << "\n----------------------------------";
cout << "\n\n Enter your choice: ";
cin >> ah;
return ah; // return statement
}
else if (ch == 3)
{
// exit(0); don't write this here, call the exit inside main()
return 3; // 3 or anything, you can return other values if you want
}
}
And in main:
int ch = menu();
if (ch == 3) exit(0);
Don't forget about return statements when writing functions.
Important note: Do not use ambiguous names for variables/functions/classes etc. For example, what does ah or ch really mean? How people reading your cryptic code are supposed to know that? Always try to use descriptive names.
What the code does is ask the user which card he wants and prints out a statement depending on which card is chosen.
My aim is to loop back to the card select function if numbers other than 1,2 and 3 are entered.
There is also a for loop which allows this process to go around multiple times.
What is the best way and how can I do this?
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
cardchoice = CardSelect();
if (cardchoice == 1) {
cout << "You got hearts" << endl;
loop = false;
} else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
loop = false;
} else if (cardchoice == 3) {
cout << "You got joker" << endl;
loop = false;
} else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
Change return type of CardSelect() to void, since your simply printing some statements in that function:
void CardSelect()
{ // Your cout statements
}
Call that in main(), and use a switch case for your cardchoice variable.
If you want to keep running the switch statement till you get a valid input, put everything in an inifinte loop (such as a while(1)) and set an exit condition by setting a boolean to true (set it to false initially) and using break when condition is satisified, to get out of the loop:
int main()
{
while(1)
{
bool valid = false;
CardSelect(); // call to your function
int cardchoice;
cin >> cardchoice;
switch(cardchoice)
{
case 1:
cout << "You got hearts" << endl;
valid = true;
break;
case 2:
cout << "You got diamonds" << endl;
valid = true;
break;
case 3:
cout << "You got joker" << endl;
valid = true;
break;
default:
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
break;
} if(valid) break;
}
}
you should not call cardchoice = CardSelect();.
This call is overwriting cardchoice with 0. Remove this call.
You print values to see what is happening. Its a good way of learning.
Hope this will help.
First, what you are looking for is continue, second you need to get rid of this line which makes no sense :
cardchoice = CardSelect();
as it erases user input
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
if (cardchoice == 1) {
cout << "You got hearts" << endl;
}
else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
}
else if (cardchoice == 3) {
cout << "You got joker" << endl;
}
else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
Program should begin with asking , whether to restock or continue with the current stock. The case 1 ( restock ) works perfectly , however the second case , to continue with the previous stock , returns zeros always if any of the products is zeroed.
In the textfile I have:
Milk: 10
Eggs: 2
Water: 7
Burrito: 10
Bread: 12
exit
How can i fix that ?
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
string productName[5] = { "Milk", "Eggs", "Water", "Burrito", "Bread" };
//int productAmount[5] = { 5,12,10,4,7};
int productAmount[5];
int productPick;
int defaultPick;
int productBuy;
fstream productFile; //we create file
void loadFromFile()
{
productFile.open("productsfile.txt", ios::in);
if (productFile.good() == false)
{
cout << "Unable to load the file. Try again later." << endl;
productFile.close();
exit(0);
}
else
{
ifstream productFile("productsfile.txt");
if (productFile.is_open())
{
cout << "How may I help you?" << endl;
string line;
while (getline(productFile, line))
{
// using printf() in all tests for consistency
cout << line.c_str() << endl;
}
productFile.close();
}
}
}
void saveToFile() //this function saves in the text file the data we've globally declared. It is used only if you want to declare new variables.
{
productFile.open("productsfile.txt", ios::out);
for (int i = 0; i < 5; i++)
{
productFile << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
productFile << "6. Exit" << endl;
productFile.close();
}
void askIfDefault()
{
cout << "Do you want to come back to default stock?" << endl;
cout << "1. Yes " << "2. No " << endl;
cin >> defaultPick;
switch (defaultPick)
{
case 1:
for (int i = 0;i < 5;i++)
{
productAmount[i] = 10;
}
saveToFile();
loadFromFile();
break;
case 2:
loadFromFile();
break;
default:
cout << "I don't understand." << endl;
exit(0);
break;
}
}
void productCheck()
{
if (productAmount[productPick - 1] <= 0 || productAmount[productPick - 1] < productBuy)
{
cout << "Unfortunately we have no more " << productName[productPick - 1] << " in stock. Please choose other product from the list below: " << endl;
productAmount[productPick - 1] = 0;
}
else
{
productAmount[productPick - 1] -= productBuy;
}
}
void listOfProducts()
{
cout << "How may I help you?" << endl;
for (int i = 0; i < 5; i++)
{
cout << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
cout << "6. Exit" << endl;
}
void order()
{
cin >> productPick;
switch (productPick)
{
case 1:
cout << "How many bottles?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 2:
cout << "How many cartons?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 3:
cout << "How many multi-packs?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 4:
cout << "How many portions?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 5:
cout << "How many batches?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 6:
cout << "See you soon!" << endl;
saveToFile();
system("pause");
break;
case 666:
cout << "You cannot use the secret magic spells here." << endl;
saveToFile();
exit(0);
break;
default:
cout << "Please pick the existing product: " << endl;
saveToFile();
order();
break;
}
}
int main()
{
askIfDefault();
order();
cout << endl;
while (true && productPick != 6)
{
listOfProducts();
order();
saveToFile();
cout << endl;
}
return 0;
}
Maybe unless declaring one global fsteam productFile, try to declare the it inside each of both functions that are using it: 'loadFromFile()' and 'saveToFile()' respectively. At the beginning of them. It should be fine then.
Let me make a few additional suggestions about your code - because it's a bit difficult to follow:
Choose function names which reflect what the function does - and don't do anything in a function which exceeds what its name indicates. For example, if you wrote a function called ask_whether_to_restock() - that function should ask the question, and perhaps even get the answer , but not actually restock even if the answer was "yes" - nor write anything to files. Even reading information from a file is a bit excessive.
If you need to do more in a function than its name suggests - write another function for the extra work, and yet another function which calls each of the first two and combines what they do. For example, determine_whether_to_restock() could call read_current_stock_state() which reads from a file, and also print_stock_state() and, say, get_user_restocking_choice().
Try to avoid global variables. Prefer passing each function those variables which it needs to use (or references/pointers to them if necessary).
Don't Repeat Yourself (DRI): Instead of your repetitive switch(produtPick) statement - try writing something using the following:
cout << "How many " << unit_name_plural[productPick] << "?" << endl;
with an additional array of strings with "bottles", "cans", "portions" etc.
For some reason, it goes into the cin statement the first time but then skips it every other time in this code. After running it a few times, I realized it goes into the default case for some reason without even asking for the user input. Why?
Here's the code. It's a menu with a huge switch statement. The functions inside the switch statements aren't relevant here since it's just the overall loop.
int main()
{
Document* myDocs = new Document[10];
int docCount = 0;
bool menu = true;
int userInput = 0;
while ( menu == true )
{
//int userInput = 0;
userInput = 0;
cout << "----------------MENU----------------" << endl << endl;
cout << " --------(1) LOAD DOCUMENT (1)--------- " << endl << endl;
cout << "--------(2) OUTPUT DOCUMENT (2)--------" << endl << endl;
cout << " --------(3) ANALYZE DOCUMENT (3)-------- " << endl << endl;
cout << " ------(4) COMPARE TWO DOCUMENTS (4)------ " << endl << endl;
cout << " ----------(5) ENCRYPT (5)---------- " << endl << endl;
cout << "-----------(6) DECRYPT (6)----------" << endl << endl;
cout << "-------------(7) EXIT (7)--------------" << endl << endl;
cin >> userInput;
string docName;
string outputLoc;
switch (userInput)
{
case 1:
// Function
break;
case 2:
// Function
break;
case 3-8:
// Function
break;
default:
break;
}
Basically, I first enter the first userinput. Let's say I enter 1. Then it goes into case 1. But then after it gets out of case 1, it goes into an infinite loop that keeps displaying the menu. Shouldn't it stop at the cin statement? That's what I dont understand.
EDIT::
Case 1 is the primary one i'm worried about since I'm trying them 1 by and 1 and case 1 doesn't work.
This is the full code for case 1:
case 1: // Load Document
{
string inputLoc;
cout << "Please input the document name:" << endl;
cin >> docName;
myDocs[docCount].setName(docName);
myDocs[docCount].id = docCount;
cout << "Input Location: " << endl;
cin >> inputLoc;
myDocs[docCount].loadDocument(inputLoc);
docCount++;
break;
}
I'm starting to speculate there is something wrong with my loadDocument function.
Here is the code for that:
void Document::loadDocument(string name)
{
ifstream myFile(name);
int numOflines = 0;
string theLine;
char words;
while (myFile.get(words))
{
switch (words)
{
case '.':
numOflines++;
break;
case '?':
numOflines++;
break;
case '!':
numOflines++;
break;
}
}
lineCount = numOflines;
setLineCt(numOflines);
arr = new Line[lineCount];
myFile.close();
char theChar;
ifstream myFile2(name);
int key = 0;
if (myFile2.is_open())
{
for ( id = 0; id < lineCount; id++ )
{
while (myFile2>> noskipws>>theChar && theChar != '.' && theChar != '!' && theChar != '?') // Changed from || to &&
{
//myFile2>> noskipws >> theChar;
theLine[key] = theChar;
key++;
}
myFile2>>theChar;
arr[id].setStr(theLine);
}
}
}
Basically I'm trying to load the document and store the word count and line count from it. Is there something wrong in it?
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