Switch statements with while loops - c++

do{
cout << "Select an option from the Menu: ";
cin >> choice;
// Validate the menu selection
while ((choice < 1) || (choice > 3)){
cout << "Incorrect input!, please enter an option from 1 to 3."<<endl;
cout<<"Enter your choice: ";
cin >> choice;
}
// Processing the users choice
if (choice != 3){
// Compute conversions
switch (choice){
case 1:
cout<<""<<endl;
cout<<"You have selected to convert Fijian Dollars to Vanuatuan Vatu."<<endl;
cout<<"Enter the amount you wish to convert: ";
cin >> amount;
conversion = amount * FJD_to_Vatu_Rate;
break;
case 2:
cout<<""<<endl;
cout<<"You have selected to convert Fijian Dollars to Samoan Tala."<<endl;
cout<<"Enter the amount you wish to convert: ";
cin >> amount;
conversion = amount * FJD_to_Tala_Rate;
break;
case 3:
cout<<"Here the history will be shown"<<endl;
cout<<""<<endl;
cout<<"Do You want to perform another conversion? (Y/N) ";
cin >> repeat;
if (repeat == 'Y'){
(This is what i want to know)
}
cout<<"Thank you for using this program, goodbye!"<<endl;
return 0;
}
// Display the monthly charges
cout << fixed << showpoint << setprecision(2);
cout << "The converted amount is: " << conversion << endl;
cout <<""<<endl;
}
} while (choice != 3);
cout<<"Thank you for using this program, goodbye!"<<endl;
return 0;
}
The above is my part of my code for a currency converter, can anyone tell me if what to do in the section where it says "this is what i want to know" so that the program asks user to enter a choice so it can process it and use the choice to compute using one of the other cases.
Thanks

Remove your if statement before switch because case 3: will never be executed in this case.
do{
cout << "Select an option from the Menu: ";
cin >> choice;
// Validate the menu selection
while ((choice < 1) || (choice > 3)){
cout << "Incorrect input!, please enter an option from 1 to 3."<<endl;
cout<<"Enter your choice: ";
cin >> choice;
}
// Processing the users choice
// Compute conversions
switch (choice){
case 1:
cout<<""<<endl;
cout<<"You have selected to convert Fijian Dollars to Vanuatuan Vatu."<<endl;
cout<<"Enter the amount you wish to convert: ";
cin >> amount;
conversion = amount * FJD_to_Vatu_Rate;
break;
case 2:
cout<<""<<endl;
cout<<"You have selected to convert Fijian Dollars to Samoan Tala."<<endl;
cout<<"Enter the amount you wish to convert: ";
cin >> amount;
conversion = amount * FJD_to_Tala_Rate;
break;
case 3:
cout<<"Here the history will be shown"<<endl;
cout<<""<<endl;
cout<<"Do You want to perform another conversion? (Y/N) ";
cin >> repeat;
if (repeat == 'Y'){
(This is what i want to know)
}
cout<<"Thank you for using this program, goodbye!"<<endl;
return 0;
// Display the monthly charges
cout << fixed << showpoint << setprecision(2);
cout << "The converted amount is: " << conversion << endl;
cout <<""<<endl;
}
} while (choice != 3);
cout<<"Thank you for using this program, goodbye!"<<endl;
return 0;
}

To restart do-while loop use continue. Logically you should print history first first, then do question\check.

Related

Undeclared identifier- C++

I am doing a project for school and keep running into this reoccurring problem, my code does not seem to run as I have "undeclared identifiers." I have tried renaming them or redefining them but the same errors keep going or more. I am using VS code at the moment and read about maybe it was VScode itself but I get the same errors regardless.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
class bankAccount {
public:
int accountNum;
string accountName;
string accountType;
double accountBalance;
double accountInterest;
double getInterest;
double updateBalance;
bankAccount(){
accountNum = 0;
accountName = "";
accountType = "";
accountBalance = 0.0;
accountInterest = 0.0;
}
void deposit()
{
long amount;
cout << "\n Please enter the amount you would like to deposit: ";
cin >> amount;
accountBalance = accountBalance + amount;
}
void withdraw()
{
long amount;
cout << "Please enter the amount you would like to withdraw: ";
cin >> amount;
if (amount <= accountBalance)
{
accountBalance = accountBalance - amount;
}
else
{
cout << "You do not have sufficient funds" << endl;
}
}
void interest(){
double getInterest;
cout << "Please enter desired interest amount: ";
cin >> getInterest;
}
void update(){
double updateBalance;
updateBalance = accountBalance * getInterest;
accountBalance += updateBalance;
}
void print(){
string print;
cout << "Welcome Back " << accountName << "," << endl;
cout << "\n Account Number: " << accountNum << endl;
cout << "\n Account Type: " << accountType << endl;
cout << "\n Current Balance: " << accountBalance << endl;
cout << "\n Account Interest: " << accountInterest << endl;
}
void openAccount(){
cout << "Enter Account Number: ";
cin >> accountNum;
cout << "Enter Account Holders Name: ";
cin >> accountName;
cout << "Enter Account Type: ";
cin >> accountType;
cout << "Enter Initial Balance: ";
cin >> accountBalance;
cout << "Enter Interest Rate: ";
cin >> accountInterest;
}
};
int main() {
int choice;
do
{
cout << "Please select the following options ";
cout << "\n 1:View Account";
cout << "\n 2: Open Account";
cout << "\n 3: Deposit" ;
cout << "\n 4: Withdraw ";
cout << "\n 5: Update account";
cin >> choice;
switch (choice)
{
case '1':
print ();
break;
case '2':
openAccount();
break;
case '3':
deposit();
break;
case '4':
withdraw();
break;
case '5':
updateBalance();
break;
}
} while (case !=5);
}
suggested creating an instance of class bankAccount somewhere before switch statement and call the functions like, instance_of_bankAccount.functionName();
At end of loop instead of (case !=5) it should be (choice != 5)
The problem with your code is that you do not have any instance of the class bankAccount, which means you try to call the function which actually does not exist. To fix it, you should create an object of the bankAccount type before the loop in which you can select the operation you want to perform:
int main() {
int choice;
bankAccount bankAcc; // this creates the object we need
do ...
And then for every case you wanted to call the function f(), add prefix bankAcc., so it becomes bankAcc.f(). In your code, it would be:
switch (choice) {
case '1':
bankAcc.print();
break;
case '2':
bankAcc.openAccount();
break;
case '3':
bankAcc.deposit();
break;
case '4':
bankAcc.withdraw();
break;
case '5':
bankAcc.updateBalance();
break;
}
Thanks to it, all functions called will know that they belong to bankAcc and they will change properties only of this particular object.
There is also another mistake in your code: did you really mean to use chars in your switch? At the moment cin >> choice reads an int, saves it in choice and then in switch it gets compared with all values corresponding to cases. The problem is that 1 is very different from '1' (which is casted to the value 49), so inputted int will never satisfy conditions from the menu you print.
Also, while (case !=5) should be changed to while (choice != 5).

Saving multiple output in a text file in c++

Still trying to learn c++. Our prof wants us to make a program wherein the output of the temperature will be saved in a text file. The variable result is the output that i want to get save. Although the code works and saves the result, the problem is it only saves the first result. I've put a limit, for now i only want to save at least 5 results.
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main()
{
double value, the_result, result;
int choice;
ofstream file;
file.open("output.txt");
do {
cout <<"\n\nChoose among the following:"
"\n1 = Celsius to Fahrenheit"
"\n2 = Celsius to Kelvin"
"\n3 = Fahrenheit to Celsius"
"\n4 = Fahrenheit to Kelvin"
"\n5 = Kelvin to Celsius"
"\n6 = Kelvin to Fahrenheit"
"\n7 = Exit"
"\n\nChoice:\n";
cin >> choice;
switch (choice){
case 1:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value*9/5+32;
cout <<"The result is ~"<< result << "\370";
}
break;
case 2:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value+273.15;
cout <<"The result is ~"<< result << "K";
}
break;
case 3:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
the_result = value-32;
result = the_result*5/9;
cout <<"The result is ~"<< result << "\370" << "F";
}
break;
case 4:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
the_result = value + 459.67;
result = the_result*5/9;
cout <<"The result is ~"<< result << "K";
}
break;
case 5:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value - 273.15;
cout <<"The result is ~"<< result << "\370";
}
break;
case 6:
cout<<"Enter Value"<< endl;
if (!(cin >> value )){
cout << "Invalid Input. Please Try Again!!";
cin.clear();
cin.ignore(123, '\n');
}else{
result = value*9/5-459.67;
cout <<"The result is ~"<< result << "\370" << "F";
}
break;
case 7:
return EXIT_SUCCESS;
break;
}
for (double i=0; i<5; i++){
file << result<< endl;
}
file.close();
}
while (choice !=7);
}
Just to expand on AProgrammer's comment - The problem is after the first iteration you are trying to write to a file that you have already closed and not reopened. So as suggested you should move the file.close() outside of the do while loop

C++ Program menu using do while and switch

I am able to display the program menu to the user, but I can't get the actual math to execute. For example, when I enter 2 it only displays 0, instead of letting me enter two integers and then either multiplying them or adding them. How can I get it to allow the user to enter options for 1, 2, or 3, and then have it do what they entered?
#include <iostream>
using namespace std;
int main()
{
int choice;
int numberOne = 0;
int numberTwo = 0;
int sumOfTwoNumbers = 0;
int productOfTwoNumbers = 0;
do{
cout <<"Please select one of the following options: \n";
cout << "1: Enter two integer values\n"
"2: Add the two values\n"
"3: Multiply the two values\n"
"4: Exit\n";
cout << "Enter your selection (1, 2,3 or 4): ";
std::cin >> choice;
switch (choice)
{
case 1:
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
break;
case 2:
sumOfTwoNumbers = numberOne + numberTwo;
cout << sumOfTwoNumbers << endl;
break;
case 3:
productOfTwoNumbers = numberOne * numberTwo;
cout << productOfTwoNumbers << endl;
break;
case 4:
cout << "You have chosen Exit, Goodbye.";
break;
default:
cout<< "Your selection must be between 1 and 4!\n";
break;
}
}while(choice!= '4');
return 0;
}
You only ask for the two numbers in case 1. In the other options the numbers are left as their default value of 0. You need to make sure that you assign the two numbers no matter which option is chosen. Also your cases don't make much sense as all of the options require inputting two numbers. I remove case 1 and simply move the lines
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
Above the switch statement:
cout <<"Please select one of the following options: \n";
cout <<
"1: Add the two values\n"
"2: Multiply the two values\n"
"3: Exit\n";
cout << "Enter your selection (1, 2, or 3): ";
std::cin >> choice;
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
switch (choice)
{
case 1:
sumOfTwoNumbers = numberOne + numberTwo;
cout << sumOfTwoNumbers << endl;
break;
case 2:
//etc

c++ Input Validation printing twice?

Don't know why it is printing twice. This is just practice I am trying to use cin.clear() / cin.ignore though. Trying to write a menu with functions inside switch statements.
#include <iostream>
#include <iomanip>
using namespace std;
void showMenu();
void showFees(double, int);
int main()
{
int choice;
int months;
const int ADULT_CHOICE = 1;
const int CHILD_CHOICE = 2;
const int SENIOR_CHOICE = 3;
const int QUIT_CHOICE = 4;
const double ADULT = 40.0;
const double CHILD = 20.0;
const double SENIOR = 30.0;
do
{
showMenu();
cin >> choice;
while (choice < ADULT_CHOICE || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin.clear();
cin.ignore(INT_MAX, '\n');
}
if (choice != QUIT_CHOICE)
{
cout << "For how many months? ";
cin >> months;
switch (choice)
{
case ADULT_CHOICE:
showFees(ADULT, months);
break;
case CHILD_CHOICE:
showFees(CHILD, months);
break;
case SENIOR_CHOICE:
showFees(SENIOR, months);
break;
}
}
} while (choice != QUIT_CHOICE);
system("pause");
return 0;
}
void showMenu()
{
cout << "\nHealth Club Membership Menu" << endl << endl;
cout << "1. Standard Adult Membership" << endl;
cout << "2. Child Membership" << endl;
cout << "3. Senior Citizen Membership" << endl;
cout << "4. Quit the Program" << endl << endl;
cout << "Enter your choice: ";
}
void showFees(double memberRate, int months)
{
cout << "The total charges are $" << (memberRate * months) << endl;
}
This is what it's printing. I'm fairly new c++, so I'm not really sure what's wrong. Is it the spacing? No clue.
Health Club Membership Menu
1. Standard Adult Membership
2. Child Membership
3. Senior Citizen Membership
4. Quit the Program
Enter your choice: 0
Please enter a valid menu choice: Please enter a valid menu choice: 0
Please enter a valid menu choice:
You have forgotten to read input again:
cin >> choice;
while (choice < ADULT_CHOICE || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin.clear();
cin.ignore(INT_MAX, '\n');
}
You read your input once. Then you go into the while check choice, You do cin.clear() and cin.ignore() and once again your loop executes as no new data has been passed: This should do the job:
cin >> choice;
while (choice < ADULT_CHOICE || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin.clear();
cin.ignore(INT_MAX, '\n');
cin >> choice;
}
The input stream looks like this:
0\n
You first read the 0, and now the stream is
\n
The 0 is invalid, so you print "Please enter a valid menu choice: " and skip over the newline.
The stream is now empty.
Since the value of choice hasn't changed, it's still invalid and you print "Please enter a valid menu choice: " again.
This time the input stream is empty, so the ignore has to wait for the next newline, and that's why you're getting two outputs only the first time.
If you instead had done the output after you were done with the input processing:
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Please enter a valid menu choice: ";
the output woldn't have been repeated.
A different bug is that the loop never exits, even if you input a valid value.
The reason for this is that you never read a new value for choice.
You need to add
cin >> choice;
at the end of the validation loop.
Problem is here:
while (choice < ADULT_CHOICE || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin.clear();
cin.ignore(INT_MAX, '\n');
}
Try this code. You must read value to variable choice again.
while (choice < ADULT_CHOICE || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: " << endl;
cin >> choice;
cout << endl;
}

while loop infinite validation response to incorrect input

In the case deposit section i have written a loop to validate that the user input is a integer but upon entering something other than an integer it assigns that to the variable credit and repeatedly displays "Please enter an amount greater than £1" i have tried to make it clear the input upon displaying the message so the process can be repeated but i cannot seem to get it to clear the variable of the incorrect input.
#include <iostream>
#include <string>
using namespace std;
enum Menusystem // enum is a function used to convert the list of words below into numbers.
{
ShowMenu, EnterName, Account, Deposit, Withdraw, Balance, Exit
} menu;
int main()
{
string customer; // declaring variables and their data types for the menu options.
string accounttype;
string name;
int credit;
int debit;
int currentbal;
bool exit = false; // declaring variable as boolean setting it to false so that when the loop gets to false it will break the loop and exit the program.
int option = 0; // declares showmenu as a integer and sets value to 0 so that the menu will be displayed upon opening the program as in the code below the menu is displayed if option is equal to 0.
while (!exit) // initiates a while loop so that when the loop gets to false it will break the loop and exit the program.
{
switch (menu) // initiates a switch statement which will allow the program to cycle through menu options depending on the menu option the user selects.
{
case ShowMenu:
cout << "[0] - Show menu\n" // displays menu options to user.
<< "[1] - Enter Full Name\n"
<< "[2] - Enter Account Type\n"
<< "[3] - Deposit Funds\n"
<< "[4] - Withdraw Funds\n"
<< "[5] - Display Balance\n"
<< "[6] - Exit Program\n";
cin >> option;
if (option == 0) menu = ShowMenu;
else if (option == 1) menu = EnterName;
else if (option == 2) menu = Account;
else if (option == 3) menu = Deposit;
else if (option == 4) menu = Withdraw;
else if (option == 5) menu = Balance;
else if (option == 6) menu = Exit;
else menu = ShowMenu; // default case is to show the menu.
break;
case EnterName:
system("CLS");
cout << "Please enter your full name >\n";
cin >> customer;
system("CLS");
menu = ShowMenu;
break;
case Account:
menu = ShowMenu;
break;
case Deposit:
system("CLS");
cout << "Please enter an amount you wish to deposit >\n";
cin >> credit;
while (!(cin >> credit)) cout << "Please enter an amount greater than £1";
{
cin.clear();
cin.ignore(100, '\n');
}
system("CLS");
menu = ShowMenu;
break;
case Withdraw:
system("CLS");
cout << "Please enter an amount you wish to withdraw >\n";
cin >> debit;
system("CLS");
menu = ShowMenu;
break;
case Balance:
cout << credit;
cout << customer;
break;
case Exit:
break;
default:
break;
}
}
return 0;
This statement:
while (!(cin >> credit)) cout << "Please enter an amount greater than £1";
{
cin.clear();
cin.ignore(100, '\n');
}
is not doing what you think it is. It's doing the equivalent of this:
while (!(cin >> credit)) {
cout << "Please enter an amount greater than £1";
}
cin.clear();
cin.ignore(100, '\n');
You need to move the cout statement into the loop, like this:
while (!(cin >> credit)) {
cout << "Please enter an amount greater than £1";
cin.clear();
cin.ignore(100, '\n');
}