I'm working on a banking program, but I've come across a weird problem with
cin>> task;
It's supposed start up a switch. but it keeps skipping the input and ends the program.
I even have an example of this on hand, that code works, but this one doesn't I'm not sure what I'm doing wrong.
#include<iostream>
#include<conio.h>
#include<string>
#include <ctype.h>
using namespace std;
int main()
{
string name = "";
int count;
char task;
double bal = 0;
int depo, withd;
cout << "Welcome to bank of the future! Please sign in" << endl;
cin >> name;
cout << "Enter your account number." << endl;
cin >> count;
cout << "Welcome back " << name << " What would you like to do?";
cout << "\n A. Deposit \n B. Withdraw \n C. Show balance \n D. Quit" << endl;
cin >> task;
//just to check if it's being skipped over or not.
cout << "egg " << endl;
switch (task)
{
case 'A':
cout << "Enter an amount to deposit" << endl;
cin >> depo;
cout << "Prevous balance: " << bal << endl;
bal = bal + depo;
cout << "New balance: " << bal << endl;
break;
case 'B':
cout << "Enter an amount to withdraw" << endl;
cin >> withd;
cout << "Prevous balance: " << bal << endl;
bal = bal - withd;
cout << "New balance: " << bal << endl;
break;
case 'C':
cout << "Your current balance is " << bal << "\n For account: " << name << "Acount number: " << count << endl;
break;
case 'D':
cout << "Goodbye forever" << endl;
break;
}
return 0;
}
I think it may have to do with the char being upper or lower case. In the switch you specify that task is uppercase. When I tried your code with uppercase letters it worked for me, but when I entered a lowercase letter it ended the program.
Related
I am trying to build a menu on console on C++ with CodeBlock. Is for a course.
I would like to validate garbage enter by the user. For example, the user have to enter a number. If he enters a wrong number, no problem, the program work and continue. But if He enters a letter or some garbage, the program start on infinite loop.
I cannot use system(PAUSE) because I am programming on Linux.
I tried some code like cin.get() or do while with cin.get() but no result.
Here is my code :
#include <iostream>
using namespace std;
void showMenu()
{
cout << "---------------MENU --------------" << endl;
cout << "1- Check balance :" << endl;
cout << "2- Check deposit :" << endl;
cout << "3- Withdraw:" << endl;
cout << "4- Exit" << endl;
cout << "--------------------------------" << endl;
}
int main()
{
int option;
double balance = 500;
do
{
showMenu();
cout << "Option: ";
cin >> option;
cout << "\033[2J\033[1;1H";
switch(option)
{
case 1:
cout << "Balance is: " << balance << " $" << endl;
break;
case 2:
cout << "Deposit amount: " << endl;
double depositAmount;
cin >> depositAmount;
balance += depositAmount;
break;
case 3:
cout << "Withdraw amount: " << endl;
double withdrawAmount;
cin >> withdrawAmount;
if (withdrawAmount <= balance) {
balance -= withdrawAmount;
}
else {
cout << "Not enough money" << endl;
}
break;
default:
cout << "Your choice is invalid ";
do {
cout << '\n' << "Press the Enter key to continue.";
}while (cin.get() != '\n');
}
} while(option != 4);
return 0;
}
Do you have an idea how can I validate easily the garbage enter by the user ?
Thank you for your Help
It works with the code on default part : cin.clear and cin.ignore(). This last one is important. Thank you to user4581301
#include <iostream>
using namespace std;
void showMenu()
{
cout << "---------------MENU --------------" << endl;
cout << "1- Check balance :" << endl;
cout << "2- Check deposit :" << endl;
cout << "3- Withdraw:" << endl;
cout << "4- Exit" << endl;
cout << "--------------------------------" << endl;
}
int main()
{
int option;
double balance = 500;
do
{
showMenu();
cout << "Option: ";
cin >> option;
cout << "\033[2J\033[1;1H";
switch(option)
{
case 1:
cout << "Balance is: " << balance << " $" << endl;
break;
case 2:
cout << "Deposit amount: " << endl;
double depositAmount;
cin >> depositAmount;
balance += depositAmount;
break;
case 3:
cout << "Withdraw amount: " << endl;
double withdrawAmount;
cin >> withdrawAmount;
if (withdrawAmount <= balance) {
balance -= withdrawAmount;
}
else {
cout << "Not enough money" << endl;
}
break;
default:
cout << "\033[2J\033[1;1H"; //for clean screen with Linux
cout << "Your choice is invalid " << endl;
cin.clear();
cin.ignore();
}
} while(option != 4);
return 0;
}
I am writing a "vending machine/grocery shopping" code in C++ where I have a menu of 5 items and the user can choose to add as my items as they want. The price is calculated at the end.
Since the user can add as many items they want, I used a while loop to so they can "continue shopping." However, I was not able to successfully do this because they code would keep running. I tried to put the switch statement in a function but did not call the "reply" properly.
Could someone help me with this code, specifically the while loop and switch statement function called int shoppingCart(). If someone could help me with abstracting this code that would be great!)
Code below (this is the original, I put an edited one below):
#include <iostream>
using namespace std;
void vendingMachine() {
cout << "1. Popcorn: $2" << endl;
cout << "2. Coconut Clusters: $3" << endl;
cout << "3. Granola Bar: $2.50" << endl;
cout << "4. Trail Mix: $1.50" << endl;
cout << "5. Chocolate: $1" << endl;
cout << "Press 0 to checkout" << endl;
}
int main() {
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter you selection: " << flush;
int input;
cin >> input;
float cost;
switch (input) {
case 1:
cout << "You added Popcorn to your cart." << endl;
cost = 2;
break;
case 2:
cout << "You added Coconut Clusters to your cart." << endl;
cost = 3;
break;
case 3:
cout << "You added Granola Bar to your cart." << endl;
cost = 2.50;
break;
case 4:
cout << "You added Trail Mix to your cart." << endl;
cost = 1.50;
break;
case 5:
cout << "You added Chocolate to your cart." << endl;
cost = 1;
break;
case 6:
cout << "Checkout" << endl;
break;
default:
cout << "Please select an item from the menu" << endl;
}
cout << "Continue shopping (y/n): " << flush;
string reply;
cin >> reply;
while(reply == "y") {
cout << "Enter your selection: " << flush;
int input;
cin >> input;
float cost;
switch (input) {
case 1:
cout << "You added Popcorn to your cart." << endl;
cost = 2;
break;
case 2:
cout << "You added Coconut Clusters to your cart." << endl;
cost = 3;
break;
case 3:
cout << "You added Granola Bar to your cart." << endl;
cost = 2.50;
break;
case 4:
cout << "You added Trail Mix to your cart." << endl;
cost = 1.50;
break;
case 5:
cout << "You added Chocolate to your cart." << endl;
cost = 1;
break;
case 6:
cout << "Checkout" << endl;
break;
default:
cout << "Please select an item from the menu" << endl;
}
cout << "Continue shopping (y/n): " << flush;
string reply;
cin >> reply;
break;
}
cout << "Proceding to checkout..." << endl;
cout << "Pay amount: $" << flush;
float money;
cin >> money;
if (money > cost) {
float change = money-cost;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == cost) {
cout << "Thank you! Have a nice day!." << endl;
}
if (money < cost) {
float amountOwed = cost-money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: " << flush;
float payment;
cin >> payment;
if (payment > amountOwed) {
float change2 = payment-cost;
cout << "Thank you! You have $" << change2 << " change." << endl;
}
if (payment == amountOwed) {
cout << "Thank you! Have a nice day!." << endl;
}
if (payment < amountOwed) {
cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
}
}
return 0;
}
Edited code:
#include <iostream>
using namespace std;
void vendingMachine() {
cout << "1. Popcorn: $2" << endl;
cout << "2. Coconut Clusters: $3" << endl;
cout << "3. Granola Bar: $2.50" << endl;
cout << "4. Trail Mix: $1.50" << endl;
cout << "5. Chocolate: $1" << endl;
cout << "Press 0 to checkout" << endl;
}
int processSelection() {
cout << "Enter your selection: " << flush;
int input;
cin >> input;
return input;
}
int shoppingCart() {
int selection = processSelection();
float cost;
switch (selection) {
case 1:
cout << "You added Popcorn to your cart." << endl;
cost = 2;
break;
case 2:
cout << "You added Coconut Clusters to your cart." << endl;
cost = 3;
break;
case 3:
cout << "You added Granola Bar to your cart." << endl;
cost = 2.50;
break;
case 4:
cout << "You added Trail Mix to your cart." << endl;
cost = 1.50;
break;
case 5:
cout << "You added Chocolate to your cart." << endl;
cost = 1;
break;
case 6:
cout << "Checkout" << endl;
break;
default:
cout << "Please select an item from the menu" << endl;
}
cout << "Continue shopping (y/n): " << flush;
string reply;
cin >> reply;
return reply;
}
int main() {
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
int reply = shoppingCart();
float cost;
while(reply == "y") {
processSelection();
shoppingCart();
}
cout << "Proceding to checkout..." << endl;
cout << "Pay amount: $" << flush;
float money;
cin >> money;
if (money > cost) {
float change = money-cost;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == cost) {
cout << "Thank you! Have a nice day!." << endl;
}
if (money < cost) {
float amountOwed = cost-money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: " << flush;
float payment;
cin >> payment;
if (payment > amountOwed) {
float change2 = payment-cost;
cout << "Thank you! You have $" << change2 << " change." << endl;
}
if (payment == amountOwed) {
cout << "Thank you! Have a nice day!." << endl;
}
if (payment < amountOwed) {
cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
}
}
return 0;
}
It looks like you're making great progress learning to code. Some thoughts:
Abstract duplicate code. Your switch statement is identical in two places. That makes it easy for bugs to appear! For example, if the price of one item changes, you might forget to update it in one place but not the other, which could lead to tricky bugs.
You have a break statement at the end of the while loop. Do you want to break on every iteration? Probably not. When do you want to break out of the loop? Under what conditions do you not want to continue? Think about the control flow, and how while loops work. While some condition is true, continue looping. Once it's false, stop looping. What is that condition? Is it just reply == y? That works on the first iteration, what about other iterations?
Some of you if statements say things like "have a good day." That sounds like a good time to break out of the loop to me. What do you think?
For a project I have to write an application that calculates the price of gas. The code works great, but I noticed something that will probably get points deducted. My total price doesn't include a dollar sign. I am stuck on where to add them and how. Below is my code. Please help!
// FinalProject1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
const double PRICE_OF_REGULAR = 1.67;
const double PRICE_OF_SPECIAL = 1.87;
const double PRICE_OF_SUPER = 1.99;
int main()
{
cout << "Gas Pump Calculator!" << endl;
double numberOfGallons;
cout << "Please enter number of gallons needed: ";
cin >> numberOfGallons;
cout << endl;
cout << "1. Regular" << endl;
cout << "2. Special" << endl;
cout << "3. Super+" << endl;
cout << endl;
int choice;
cin >> choice;
switch (choice)
{
case 1:
cout << endl;
cout << "You chose regular. The total price of gas is: " << (numberOfGallons * PRICE_OF_REGULAR);
cout << endl;
break;
case 2:
cout << endl;
cout << "You chose special. The total price of gas is: " << (numberOfGallons * PRICE_OF_SPECIAL);
cout << endl;
break;
case 3:
cout << endl;
cout << "You chose super+. The total price of gas is: " << (numberOfGallons * PRICE_OF_SUPER);
cout << endl;
break;
}
return 0;
}
Just print a dollar sign after the number:
cout << "You chose regular. The total price of gas is: "
<< (numberOfGallons * PRICE_OF_REGULAR) << "$";
//^ add dollar sign
Or before the number, depending on how you want to print it out.
cout << "You chose regular. The total price of gas is: $"
<< (numberOfGallons * PRICE_OF_REGULAR); //^ add dollar sign
Just add it before your value:
cout << "You chose regular. The total price of gas is: $"
<< (numberOfGallons * PRICE_OF_REGULAR);
Assignment:
When you enter an incorrect number of digits( 3 or 5 digits pin number) a
message should display “You have entered the incorrect pin number!!...you
must enter a four digits pin number.”
By showing the message that was display previously the program should
allow you to re-enter the correct number of digits.
The number of attempts should be three times.
When you have entered the correct number of digits a message should display
“Your pin has been accepted!!”
Each time you enter any amount of pin number it must show in asterisk.
Code:
#include <conio.h>
#include <iostream>
//#include <cstdlib.h>
#include <cmath>
using namespace std;
int main() {
string pass = "";
int attempts = 3;
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl;
cout << "< Welcome to The Bank >" << endl;
cout << "< >" << endl;
cout << "< Please Enter Pin Below >" << endl;
cout << " ^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl;
cout << "\nEnter Pin Number: " << endl;
cin >> pass;
// attempts= getch();
while (attempts <= 3) {
cout << "*";
getch();
attempts++; // take this out and it display to infinity
// }
if (pass == "1718") {
cout << " lOGIN IN..." << endl << endl;
attempts = -1;
}
else {
cout << "\nWRONT PIN-TRY AGAIN: " << endl << endl;
attempts--;
cout << " REMAINING ATTEMPTS: " << attempts << endl << endl;
}
if (attempts == 0) {
cout << "Exceed the Pin attempts. Try Later. " << endl << endl;
}
if (attempts == -1) {
cout << "********************************" << endl;
cout << "* Welcome to Magali's Bank *\n";
cout << "* Select Option: *\n";
cout << "* 1. Check Balance *\n";
cout << "* 2. Withdraw *\n";
cout << "* 3. Deposit *\n";
cout << "* 4. Exit *\n";
cout << "********************************\n";
int balance = 500;
float withdraw;
float deposit;
int user;
cout << "Enter Number: ";
cin >> user;
while (user != 4) {
switch (user) {
case 1:
cout << " Your balance is: " << balance << endl;
break;
case 2:
cout << "Enter the amount you want withdraw: ";
cin >> withdraw;
balance = balance - withdraw;
break;
case 3:
cout << "Enter the amount you want to deposit: ";
cin >> deposit;
balance = balance + deposit;
break;
default:
cout << " Need to type 1 for Balance, 2 to Withdraw, 3 to Deposit "
"and 4 to Exit. ";
}
cout << "Enter Number: ";
cin >> user;
}
cout << "\nTHANKS FOR USING THE SYSTEM!\n";
}
}
return 0;
}
Your code has lots of inefficiencies but as you requested. I'm only debugging only a part of it where you need to take input and display error.
string pass="";
int attempts=3;
const string pin = "1718";
//DO whatever you want
//while loop to take input
while (attempts >0)
{
cout << "\nEnter Pin Number: " << endl;
cin >> pass;
for(auto i : pass)
cout<<"*";
if(pass == pin){
attempts = 3;
cout<<"Your Pin has been accepted.\n";
break;}
else{
cout <<"\nWRONT PIN-TRY AGAIN: " << endl << endl;
attempts--;
cout << " REMAINING ATTEMPTS: " << attempts << endl << endl;
}
}
if (attempts == 0)
{
cout << "Exceed the Pin attempts. Try Later. "<< endl << endl;
cout<<"Your account has been locked for a day .\n";
exit(0);
}
Comment out if you didn't understand any part.
this is a project I'm working on which comes from the book I'm using to learn C++ - "Starting out with C++". I'm having a problem with the cashier portion of the project at the moment. It asks the user to enter the date, quantity, isbn, title, and price of the book. Then, it asks the user if they wish to enter another book. Regardless of whether they type "y" or "n" it continues to the next part of the program. I don't really know why the for loop doesn't repeat after I type "y" to enter another book. Also, the date is coming out with garbage at the end when it is displayed, that's another thing I need to fix. Any help would be appreciated. There is definitely more problems but the main problem is in the cashier function in the first for loop. I didn't include the whole program because it's very long.
/*
* mainmenu.cpp
* Serendipity Booksellers software
*
* Created by Abraham Quilca on 9/5/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include<iostream>
#include<iomanip>
#include<cstring>
#include"mainmenu.h"
using namespace std;
char bookTitle[20][51],
isbn[20][14],
author[20][31],
publisher[20][31],
dateAdded[20][11];
int qtyOnHand[20];
double wholesale[20];
double retail[20];;
int main()
{
int choice;
do
{
cout << "\t\t Serendipity Booksellers"<< endl;
cout << "\t\t\t Main Menu" << endl << endl;
cout << "\t\t1. Cashier Module" << endl;
cout << "\t\t2. Inventory Database Module" << endl;
cout << "\t\t3. Report Module" << endl;
cout << "\t\t4. Exit" << endl << endl;
cout << "\t\tEnter your choice: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cashier();
break;
case 2:
invmenu();
break;
case 3:
reports();
break;
case 4:
continue;
break;
default:
cout << "\t\tPlease enter a number in the range 1-4." << endl << endl;
}
}
while(choice != 4);
cout << "\t\tYou selected item 4." << endl;
return 0;
}
// Cashier function
void cashier()
{
char again;
char date[8];
int quantity[20] = {0};
char ISBN[20][20] = {0};
char title[20][40] = {0};
float price[20] = {0}, bookTotal[20] = {0}, subtotal, total, tax;
const float tax_rate = .06;
cout << "Serendipity Booksellers" << endl;
cout << " Cashier Module" << endl << endl;
for(int count = 0; count < 20; count++)
{
cout << "Date: ";
cin >> date;
cout << "Quantity of Book: ";
cin >> quantity[count];
cout << "ISBN: ";
cin >> ISBN[count];
cout << "Title: ";
cin.ignore();
cin.getline(title[count], 40);
cout << "Price: ";
cin >> price[count];
bookTotal[count] = quantity[count] * price[count];
subtotal += price[count];
cout << "Would you like to enter another book? (Y/N) ";
cin >> again;
if(again == 'N' || 'n')
count = 21; // This line will end the for loop
}
// Calculating tax and total
tax = subtotal * tax_rate;
total = subtotal + tax;
cout << "\n\nSerendipity Booksellers" << endl << endl;
cout << "Date:" << date << endl << endl;
cout << "Qty\t ISBN\t\t "
<< left << setw(40) << "Title" << "Price\t Total" << endl
<< "-------------------------------------------------------------------------------"
<< endl << endl;
for(int count = 0; count < 20; count++)
{
cout << quantity[count] << "\t " << ISBN[count] << " " << left << setw(40) << title[count]
<< setprecision(2) << fixed << "$" << setw(6) << price[count] << " $" << setw(6) << bookTotal[count]
<< endl << endl;
}
cout << "\t\t\t Subtotal" << "\t\t\t\t $" << setw(6) << subtotal << endl;
cout << "\t\t\t Tax" << "\t\t\t\t $" << setw(6) << tax<< endl;
cout << "\t\t\t Total" "\t\t\t\t $" << setw(6) << total << endl << endl;
cout << "Thank You for Shopping at Serendipity!" << endl << endl;
}
if(again == 'N' || 'n')
This doesn't do what you think it does. Look at it like this:
if((again == 'N') || ('n'))
Is again == N true OR is n true? Well n will always be true (it is a char with non-zero value) so your loop will always end immediately. What you want is:
if(again == 'N' || again == 'n')
Also, you can break out of a loop using the aptly named break keyword:
if (again == 'N' || again == 'n') {
break;
}
The problem with the loop is this line:
if(again == 'N' || 'n')
C++ doesn't know that you mean it to check again against both characters. Instead, it tries again == 'N', which fails, and then tries 'n', which - not being zero - evaluates as true.
Instead, try:
if (again == 'N' || again == 'n')
break;