How do I make a function that will terminate the program if the user says e, and loop if the user presses l at any time?
How do I make the program reask the user for number input if the user inputs letters instead of numbers? Currently, the program terminates when I input blah, for instance. My obstacle is the bool die definition: I'm not sure how to use bool die to loop instead of die (my teacher required bool die usage.)
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
bool die(const string & msg);
int main() {
// declaring variables:
unsigned QUARTERS;
unsigned DIMES;
unsigned NICKELS;
unsigned PENNIES;
double total;
cout << "********************************************************" << endl;
cout << " Welcome to Crazy Coin Counter! " << endl;
cout << "********************************************************" << endl << endl;
// user input:
//QUARTERS
do {
cout << " # QUARTERS: ";
cin >> QUARTERS;
if (cin){
if (QUARTERS < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
cout << " You must put in less than 1000 quarters! Please try again." << endl << endl << endl;
} while (QUARTERS >= 1000 );
//DIMES
do{
cout << endl << " # DIMES: ";
cin >> DIMES;
if (cin){
if (DIMES < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
if (DIMES >= 1000)
cout << " You must put in less than 1000 dimes! Please try again." << endl << endl << endl;
} while (DIMES >= 1000);
//NICKELS
do {
cout << endl << " # NICKLES: ";
cin >> NICKELS;
if (cin){
if (NICKELS < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
if (NICKELS >= 1000)
cout << " You must put in less than 1000 nickels! Please try again." << endl << endl << endl;
} while (NICKELS >= 1000);
//PENNIES
do {
cout << endl << " # PENNIES: ";
cin >> PENNIES;
if (cin){
if (PENNIES < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
if (PENNIES >= 1000)
cout << " You must put in less than 1000 pennies! Please try again." << endl;
} while (PENNIES >= 1000);
// calculations:
total = (QUARTERS * 0.25) + (DIMES * 0.1) + (NICKELS * 0.05) + (PENNIES * 0.01);
// output:
cout << endl <<endl<< "Congrats! You have $" << total << " worth of coins! " << endl << endl << endl;
}
// function definition
bool die(const string & msg){
cout << " " << msg << endl;
exit(EXIT_FAILURE);
}
Try something like this:
while ( true ) // Loop forever
{
cout << "Enter 'e' to exit:";
std::string answer;
getline(cin, answer);
if (answer == "e")
{
break; // Break out of the loop
}
else
{
cout << "\nWrong answer.\n";
continue; // The continue would start at the top of the loop.
}
}
There are many other techniques that you can find by searching StackOverflow for "c++ terminate loop".
Edit 1: Checking numerical input
The simplest method for checking numerical input is to test the result of inputting the number:
unsigned int quarters; // Using unsigned because quantities can't be negative.
cout << "Enter number of quarters: ";
if (cin >> quarters) // Input and test in same statement.
{
cout << "Your total is " << (quarters * 0.25) << "\n";
}
else
{
// Handle incorrect input
cout << "Invalid input, try again.\n";
}
Related
I can't figure out how to make my code go to the next else if statement if my user input satisfies the previous if state.
#include <iostream>
using namespace std;
int main()
{
double input;
cout << "Time Calculator\n Enter the number of Seconds: " << endl;
cin >> input;
if (input < 60)
{
cout << "The time is " << input << " seconds." << endl;
}
else if (input >= 60)
{
cout << "The time is " << input << " minutes." << endl;
}
else if (input >= 3600)
{
cout << "The time is " << input << " hours." << endl;
}
else if (input >= 86400)
{
cout << "The time is " << input << " days." << endl;
}
return 0;
}
in your code if input > 60 it will satisfy condition and will not execute else part so first check wether input > 86400 if not then check if input > 36000 if not then check for input > 60
try below code in which if conditions are reversed
#include <iostream>
using namespace std;
int main()
{
double input;
cout << "Time Calculator\n Enter the number of Seconds: " << endl;
cin >> input;
if (input < 60)
{
cout << "The time is " << input << " seconds." << endl;
}
else if (input >= 86400)
{
cout << "The time is " << input << " days." << endl;
}
else if (input >= 3600)
{
cout << "The time is " << input << " hours." << endl;
}
else if (input >= 60)
{
cout << "The time is " << input << " minutes." << endl;
}
return 0;
}
Make it other way round.
#include <iostream>
using namespace std;
int main()
{
double input;
cout << "Time Calculator\n Enter the number of Seconds: " << endl;
cin >> input;
if (input >= 86400)
{
cout << "The time is " << input << " days." << endl;
}
else if (input >= 3600)
{
cout << "The time is " << input << " hours." << endl;
}
else if (input >= 60)
{
cout << "The time is " << input << " minutes." << endl;
}
else
{
cout << "The time is " << input << " seconds." << endl;
}
return 0;
}
Hope this is what you want!
There are multiple ways to do this, you can implement a check between 2 values using conditions like >= val1 and < val2 or ensure that the order in which the checks happen is different.
#include <iostream>
using namespace std;
int main()
{
double input;
cout << "Time Calculator\n Enter the number of Seconds: " << endl;
cin >> input;
if (input < 60)
{
cout << "The time is " << input << " seconds." << endl;
}
else if (input >= 60 && input < 3600)
{
cout << "The time is " << input << " minutes." << endl;
}
else if (input >= 3600 && input < 86400)
{
cout << "The time is " << input << " hours." << endl;
}
else if (input >= 86400)
{
cout << "The time is " << input << " days." << endl;
}
return 0;
}
or another way would be to change the order, once the particular if statement is valid, it doesn't check with the rest of the if statements.
#include <iostream>
using namespace std;
int main()
{
double input;
cout << "Time Calculator\n Enter the number of Seconds: " << endl;
cin >> input;
if (input >= 86400)
{
cout << "The time is " << input << " seconds." << endl;
}
else if (input >= 3600)
{
cout << "The time is " << input << " minutes." << endl;
}
else if (input >= 60)
{
cout << "The time is " << input << " hours." << endl;
}
else if (input < 60)
{
cout << "The time is " << input << " days." << endl;
}
return 0;
}
Your if else conditions are not completely defined... you have to set those in a range... otherwise is not going to work...
if (input < 60)
{
cout << "The time is " << input << " seconds." << endl;
}
else if (input >= 60 && input < 3600))
{
cout << "The time is " << input << " minutes." << endl;
}
else if (input >= 3600 && input < 86400))
{
cout << "The time is " << input << " hours." << endl;
}
else if (input >= 86400)
{
cout << "The time is " << input << " days." << endl;
}
Why is my else, cout << "You have entered an incorrect code" still executing and writing to the screen after I enter r or R and complete the calculation and dialogue. The same does not happen when I enter p or P and follow through with that portion of my program. Sorry for the incredibly nooby question.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char service;
int number;
int minutes;
int dayMinutes;
int nightMinutes;
double bill;
double dayCharge;
double nightCharge;
double const REG_FEE = 10.00;
double const PREM_FEE = 25.00;
double const REG_MIN = 0.20;
double const PREM_DAY = 0.10;
double const PREM_NIGHT = 0.05;
cout << "Please enter your account number: ";
cin >> number;
cout << "Please enter your service type (regular or premium): ";
cin >> service;
if (service == 'r' || service == 'R')
{
cout << "How many minutes have been used for this service?: ";
cin >> minutes;
if (minutes <= 50)
{
bill = REG_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << minutes << " minutes." << endl;
}
else
{
bill = ((minutes - 50) * REG_MIN) + REG_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << minutes << " minutes." << endl;
}
}
if (service == 'p' || service == 'P')
{
cout << "How many minutes were used during the day?: ";
cin >> dayMinutes;
cout << "How many minutes were used during the night?: ";
cin >> nightMinutes;
if (dayMinutes > 75)
{
dayCharge = ((dayMinutes - 75) * PREM_DAY);
}
if (nightMinutes > 100)
{
nightCharge = ((nightMinutes - 100) * PREM_NIGHT);
}
bill = dayCharge + nightCharge + PREM_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << dayMinutes + nightMinutes << " minutes." << endl;
}
else
{
cout << "You have entered an invalid service code." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
}
return 0;
}
That's because you need this-
if (service == 'r' || service == 'R'){
// your code
}
else if(service == 'p' || service == 'P'){
//your code
}
else {
//your code
}
Problem right now with your code is that if you even enter 'r' or 'R', due to if else condition with 'p' or 'P' becomes false and else part gets executed .
That's why you needed to use if - else if format so that for an input only one part is executed.
My program is supposed to reject any input more than 1000. I do not get any errors in my code and MS Visual Studio and it lets me compile it, but when I put in 2000, it says "input successful" instead of "please try again".
I am aware that I haven't put the loop in yet, so the "please try again" will not work. However, as of now, I just want the output to say "please try again" and go on to nickels.
// This program prompts the number of coins, and outputs how many cents you have
#include <iostream>
#include <string>
using namespace std;
int main() {
// declaring variables:
unsigned QUARTERS;
unsigned DIMES;
unsigned NICKELS;
unsigned PENNIES;
double total;
cout << "********************************************************" << endl;
cout << " Welcome to Crazy Coin Counter! " << endl;
cout << "********************************************************" << endl << endl;
// user input:
cout << "# QUARTERS: ";
cin >> QUARTERS;
if (QUARTERS < 1000)
cout << " --> Input Successful!" << endl;
else if (QUARTERS >= 1000)
cout << "You cannot put in more than 1000 quarters! Please try again." << endl;
cout << endl << "# DIMES: ";
cin >> DIMES;
if (DIMES < 1000)
cout << " --> Input Successful!" << endl;
else if (DIMES>= 1000)
cout << "You cannot put in more than 1000 dimes! Please try again." << endl;
cout << endl << "# NICKLES: ";
cin >> NICKELS;
if (NICKELS< 1000)
cout << " --> Input Successful!" << endl;
else if (NICKELS>= 1000)
cout << "You cannot put in more than 1000 dimes! Please try again." << endl;
cout << endl << "# PENNIES: ";
cin >> PENNIES;
if (PENNIES < 1000)
cout << " --> Input Successful!" << endl;
else if (PENNIES >= 1000)
cout << "You cannot put in more than 1000 dimes! Please try again." << endl;
// calculations:
total = (QUARTERS * 0.25) + (DIMES * 0.1) + (NICKELS * 0.05) + (PENNIES * 0.01);
// output:
cout << endl <<endl<< "Congrats! You have $" << total << " worth of coins! " << endl << endl << endl;
return 0;
}
You are inputting different variables (e.g., DIMES, NICKLES, etc.), but always checking the value of QUARTERS. Just fix each if statement to check the variable that was just inputed (using cin), and you should be fine.
I have to write a program that simulates an ice cream cone vendor. The user inputs the number of cones, and for each cone, the user inputs the number of scoops, then the flavor(a single character) for each scoop. At the end, the total price is listed. For the pricing, 1 scoop costs 2.00, 2 scoops costs 3.00 and each scoop after 2 costs .75.
I'm having trouble with the pricing. The correct price is displayed if the user only wants one cone.
/*
* icecream.cpp
*
* Created on: Sep 14, 2014
* Author:
*/
#include <iostream>
#include <string>
using namespace std;
void welcome() {
cout << "Bob and Jackie's Ice Cream\n";
cout << "1 scoop - $1.50\n";
cout << "2 scoops - $2.50;\n";
cout << "Each scoop after 2 - $.50\n";
cout << "Ice Cream Flavors: Only one input character for each flavor.\n";
}
bool checkscoops(int scoops) {
int maxscoops = 5;
if ((scoops > maxscoops) || (scoops < 1))
return false;
else
return true;
}
bool checkcones(int cones) {
int maxcones = 10;
if ((cones > maxcones) || cones < 1)
return false;
else
return true;
}
int price(int cones, int numberofscoops) {
float cost = 0.00;
{
if (numberofscoops == 5) {
cost = cost + 5 + (.75 * 3);
}
if (numberofscoops == 4) {
cost = cost + 5 + (.75 * 2);
}
if (numberofscoops == 3) {
cost = cost + 5.75;
}
if (numberofscoops == 2) {
cost = cost + 5.00;
}
if (numberofscoops == 1) {
cost = cost + 2.00;
}
}
cout << "Total price is: " << cost << endl;
}
int buildcone(int numcones) {
char flav1, flav2, flav3, flav4, flav5;
int numberofscoops;
for (int i = 1; i <= numcones; i++) {
cout << "Enter the amount of scoops you wish to purchase. (5 max): ";
cin >> numberofscoops;
checkscoops(numberofscoops);
while (checkscoops(numberofscoops) == false) {
cout << "You are not allowed to buy more than 5 scoops and you "
"cannot buy less than one scoop. Please try again.\n";
cout << "How many scoops would you like?(5 max): ";
cin >> numberofscoops;
checkcones(numberofscoops);
}
cout << "You are buying " << numberofscoops
<< " scoops of ice cream.\n";
if (numberofscoops == 5) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << "Enter flavor 3: ";
cin >> flav3;
cout << "Enter flavor 4: ";
cin >> flav4;
cout << "Enter flavor 5: ";
cin >> flav5;
cout << " ( " << flav1 << " )/" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " ( " << flav3 << " )" << endl;
cout << " ( " << flav4 << " )" << endl;
cout << " ( " << flav5 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 4) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << "Enter flavor 3: ";
cin >> flav3;
cout << "Enter flavor 4: ";
cin >> flav4;
cout << " ( " << flav1 << " )" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " ( " << flav3 << " )" << endl;
cout << " ( " << flav4 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 3) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << "Enter flavor 3: ";
cin >> flav3;
cout << " ( " << flav1 << " )" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " ( " << flav3 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 2) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << " ( " << flav1 << " )" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 1) {
cout << "Enter a flavor: ";
cin >> flav1;
cout << " ( " << flav1 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
}
price(numcones, numberofscoops);
}
int main() {
int numberofcones;
int numberofscoops;
welcome();
cout << "How many cones would you like?(10 max) ";
cin >> numberofcones;
checkcones(numberofcones);
while (checkcones(numberofcones) == false) {
cout << "You are not allowed to buy more than 10 cones and you cannot "
"buy less than one cone. Please try again.\n";
cout << "How many cones would you like?(10 max): ";
cin >> numberofcones;
checkcones(numberofcones);
}
cout << "You are buying " << numberofcones << " ice cream cones.\n";
buildcone(numberofcones);
}
Start by changing the return value of price() to float, or the function won't be able to return the proper cost. Also, since cones is not used to compute the cost of the purchase, we don't it as a parameter:
float price(int numberofscoops)
{
float total_cost = 0.0f;
if (numberofscoops == 1) {
total_cost = 2.0f;
}
else if (numberofscoops == 2) {
total_cost = 3.0f;
}
else if (numberofscoops > 2) {
total_cost = 5.0f + ((numberofscoops-2) * 0.75f);
}
return total_cost;
}
You code could have other problems, but I think these changes will let you continue to debug and fix the code on your own.
Your while() loop is flawed. Comment your call to checkcones() as shown below. You're already calling checkcones() as the conditional in your while(), no need to evaluate again as this will sent you into a perma-loop. You've got two of these while() statements that I could see, you'll want to comment out both.
while ( checkcones( numberofcones ) == false )
{
cout << "You are not allowed to buy more than 10 cones and you cannot buy less than one cone. Please try again.\n";
cout << "How many cones would you like?(10 max): ";
cin >> numberofcones;
// THIS LINE IS THE PROBLEM :)
// checkcones(numberofcones);
}
After this fix, your program begins to work but the pricing fails. You should be able to figure that out with the answer given above.
I would also see if you can figure out how to implement a c++ class with members and methods as your current approach is very "c" like. Happy coding! :)
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;