I need to make the program loop until the user inputs "XXXX" as the name. Problem is, my code only loops once at most and exits. I have tried messing with do ... whiles for an entire day and can't seem to figure this out but I feel like i'm really close!
Edit:
You guys are awesome! Made both of the changes but now it skips the name prompt and goes straight to the deposit prompt. How would i get it to include the name prompt in the loop?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string name, XXXX;
float deposit, time, interest, total, totinterest;
int compound;
cout << left;
int flag = 0;
do {
cout << "Enter your name or XXXX to stop: ";
getline(cin, name);
cout << name << " enter the following information: " << endl;
if (name == "XXXX"){
flag = 1;
}else
{
cout << setw(60) << "\tAmount on deposit: ";
cin >> deposit;
if (!deposit || deposit < 0){
cout << "\tPlease enter a positive number! ";
}
cout << setw(60) << "\tYears on deposit: ";
cin >> time;
if (!time || time < 0){
cout << "\tPlease enter a positive number! ";
return(0);
}
cout << setw(60) << "\tNumber of times the interest is compounded per year: ";
cin >> compound;
if (!compound || compound < 0){
cout << "\tPlease enter a positive number! ";
return(0);
}
if (time >= 5)
interest = .045;
else if (time >= 4)
interest = .04;
else if (time >= 3)
interest = .035;
else if (time >= 2)
interest = .025;
else if (time >= 1)
interest = .02;
else if (time < 1)
interest = .015;
total = (deposit)*pow((1 + interest / compound), (compound * time));
totinterest = total - deposit;
cout << left << setprecision(2) << fixed;
cout << endl;
cout << setw(15) << "Name " << setw(14) << "Years" << setw(18) << "Deposit Amount" << setw(18) << "Interest Earned " << setw(18) << "Total" << endl;
cout << "===============================================================================" << endl;
cout << setw(15) << name << setw(14) << time << setw(1) << "$" << setw(17) << deposit << setw(1) << "$" << setw(17) << totinterest << setw(1) << "$" << setw(18) << total << endl;
cout << endl;
cout << "Thank you for using tax program. Have a nice day. " << endl;
return(0);
}
} while (flag = 0);
}
return(0) will get you out of the main. Remove that line and retry.
return(0) will exit the main() and the program will terminate. Hence, remove it from the source.
Also the condition in while (flag = 0) will always return false. Change it to while (flag == 0) otherwise it would result in a loop that iterates only once.
And finally, you need <math.h> for the pow() function.
#include <math.h>
Because you are using = instead of == in while condition.
Change flag = 0 to !flag or flag==0.
Apart from this, you have return 0 which is unconditional. This return statement will make the program to exit anyhow.
You have to include
#include <math.h>
for your pow function to work. I get an error that pow is not defined.
Firstly, you want your while condition to be
while(flag == 0) and not while (flag = 0)
Also, if the user enters an invalid value of time or deposit or compound(such as less than 0), then your code prints out an error message and quits. Instead, you want to put a while loop there that keeps prompting the user for a valid input as long they keep giving an incorrect input.
Finally, you wanna be using something like myString.compare(otherString) instead of the == operator
You have a return(0); in your else clause. Also, you have = instead of == in your while loop, which (after you remove the return statement) is a recipe for an infinite loop.
Related
I was doing a school assignment involving functions, it wasn't too hard until I learned I needed to reject negative numbers as variables. It doesn't reject the numbers and instead just skips the next variable and then will loop to a seemingly random variable random variables in the code when the function completes.
void InPatient()
{
int DaysIn = 0;
double DailyRate{};
double MedicationCharges{};
double ServiceCharges{};
cout << "Please enter number of days patient stayed (Rounded up):" << endl;
cin >> DaysIn;
//I tried to use while statements to solve this problem and it hasn't worked
while (DaysIn != 50000000000)
{
if (DaysIn >= 0)
{
cout << "Please enter hospital's daily rate as a decimal (Ex: .35, .265):" << endl;
cin >> DailyRate;
}
else if (DaysIn < 0)
{
cout << "That is not a valid number in the system" << endl;
}
if (DailyRate >= 0)
{
cout << "Please enter medicine charges:" << endl;
cin >> MedicationCharges;
}
else if (DailyRate < 0)
{
cout << "That is not a valid number in the system" << endl;
}
//I tried these else if statements to reject negative numbers and loop back but it just says "It doesn't work" and continues on.
if (MedicationCharges >= 0)
{
cout << "Please enter service charges (for lab testing or whatnot):" << endl;
cin >> ServiceCharges;
}
else if (MedicationCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
if (ServiceCharges >= 0)
{
double DaysInFee = DaysIn / DailyRate;
double HospitalBill = DaysInFee + MedicationCharges + ServiceCharges;
cout << "Patient's Stay Fee: $" << DaysInFee << "\n";
cout << "Medication Charges: $" << MedicationCharges << "\n";
cout << "Service Charges: $" << ServiceCharges << "\n";
cout << "Patient's total is $" << std::setprecision(2) << std::fixed << HospitalBill << " " << "today." << endl;
}
else if (ServiceCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
}
}
void OutPatient()
{
double MedicationCharges = 0;
double ServiceCharges{};`
//I've done something different down here, but it does the exact same thing
while (MedicationCharges != 50000000000)
{
cout << "Please enter medicine charges:" << endl;
cin >> MedicationCharges;
cout << "Please enter service charges (for lab testing or whatnot):" << endl;
cin >> ServiceCharges;
double HospitalBill = MedicationCharges + ServiceCharges;
cout << "Medication Charges: $" << MedicationCharges << "\n";
cout << "Service Charges: $" << ServiceCharges << "\n";
cout << "Patient's total is $" << std::setprecision(2) << std::fixed << HospitalBill << " " << "today." << endl;
if (MedicationCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
//These just say "These don't work" but let's the code use them anyways.
else if (ServiceCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
}
}
As stated in the code, I have used while and if statements to reject negatives, but it doesn't reject them.
Add a continue in your else if blocks to restart the while-loop after an incorrect input
Alternatively, add a break or return statement to leave the loop or function. It depends what you want to do in the error case.
This question already has answers here:
Immediate exit of 'while' loop in C++ [closed]
(10 answers)
Closed 3 years ago.
Ok before anyone bashes me, I checked every forum to try to help me solve this problem but unfortunately cannot solve it. Can someone point to the right direction to solve this? I am trying to exit this do while loop immediately when inputting the value -1. For example I want the output to look like this when I input -1:
Enter the expected number of hours charging:
//user enters -1
Exiting...
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
float hour;
float Network1, Network2, Network3;
do {
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
Network1= (1 * hour) + 10;
Network2= (2.50 * hour);
Network3 = (0.50 * hour) + 20;
cout << "Your expected costs are: " << endl;
cout << "Network 1: $" << fixed << setprecision(2) << Network1 << endl;
cout << "Network 2: $" << fixed << setprecision(2) << Network2 << endl;
cout << "Network 3: $" << fixed << setprecision(2) << Network3 << endl;
if(Network1 < Network2 && Network1 < Network3){
cout << "The lowest cost network is $" << Network1 << endl;
}
else if (Network2 < Network1 && Network2 < Network3){
cout << "The lowest cost network is $" << Network2 << endl;
}
else{
cout << "The lowest cost network is $" << Network3 << endl;
}
}
while (hour != -1) ;
cout << "Exiting..." << endl;
return 0;
}
There is two ways:
You can check input right after read
cin >> hour;
if (hour == -1) {
break;
}
You can use while loop and read value twice. First one before the first iteration and the second in the end
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
while (hour != -1) {
// ...
cout << "Enter one more value:" << endl;
cin >> hour;
}
There are two basic ways of doing this, the neanderthal way and the cromagnon way.
The neanderthal way;
for(;;) {
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
if (!cin || hour == -1) break;
...
The cromagnon way:
while (std::cout << "Enter the expected number of hours charging: \n" &&
std::cin >> hour &&
hour! = -1) {
...
Methods that do not involve checking of cin properly belong to pithecanthrops.
I'm having a problem with the random generated number result not matching with the user input and it only outputs the first statements instead of falling to else if the user guessed wrong.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
int bank = 10;
int heads = 0;
int tails = 1;
char response;
string headsTails;
int coinToss = rand() % 2;
srand(static_cast<int>(time(0)));
cout << "Welcome to the coin flip game. It cost a dollar to play. " << endl;
cout << "If you guess correctly you will win $2.00 dollars " << endl;
cout << "Do you want to play? (Y/N) " << endl;
cin >> response;
while (toupper(response) == 'Y')
{
cout << "Your bank is $" << bank << " dollars." << endl;
cout << "Enter head or tails (H/T)" << endl;
cin >> response;
coinToss = rand() % 2;
headsTails = coinToss ? "Heads" : "Tails";
if (coinToss == heads || coinToss == tails)
{
cout << "Winner! The coin flip came up " << headsTails << endl;
cout << "Would you like to play again? (Y/N) " << endl;
cin >> response;
bank += 2;
}
else
{
cout << "Sorry, you lose. The coin flip came up " << headsTails <<
endl;
cout << "Would you like to play again? (Y/N) " << endl;
cin >> response;
bank -= 1;
}
}
cout << "Thanks for playing! Your bank is " << bank << endl;
cout << "Please come again! " << endl;
return 0;
}
if (coinToss == heads || coinToss == tails)
That condition is wrong, it will always evaluate to true since you set coinToss to 0 or 1 yourself.
You have to use the response variable you ask of the user, something like:
int guess = response == 'T' ? 1 : 0; // convert the user input to the same values used throughout the program.
if(guess == coinToss)
//won..
else
//lost..
I am making a Slot Machine program in C++ as a class assignment. The program is supposed to take a percentage of your total credit (starting at 1000.00) and generate three random numbers to signify the three slot numbers. The user wins if all three numbers match. The game will keep going just so long as the user still has credit, and the program should always ask the user if they want to continue.
I have gotten basically everything I need for the program to work, but my issue is that whenever I play the game and I get a match, it does not prompt the user to enter more credit. Instead it just ends the program. I figured it has something to do with the way I wrote my while loop because the condition only applies for if the numbers don't match, and since they don't match it isn't able to check the first if statement within the loop. I tried using a do-while, but it's the same situation. How can I rearrange the code so it will prompt the user to bet again even if they won?
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
/* Start: Do Not Change */
const int MAX = 5;
const int MIN = 1;
// This function takes tree ints as parameters
// and sets them to a random number
int spin(int & n1, int & n2, int & n3)
{
n1 = rand()%(MAX-MIN)+MIN;
n2 = rand()%(MAX-MIN)+MIN;
n3 = rand()%(MAX-MIN)+MIN;
}
/* End: Do Not Change */
int main()
{
int slot1, slot2, slot3;
double percent;
double credits = 1000.00;
char keepPlaying;
srand (time(NULL));
cout << "Welcome to the slots, you have 1,000.00 credits.\n"
<< "What percentage of credits do you want to bet(0-1)? ";
cin >> percent;
spin(slot1, slot2, slot3); // At this point slot1-3 all have a random value between 1 and 5
//spin function
cout << "Slot value = " << slot1 << "-" << slot2 << "-" << slot3 << endl;
while (slot1 != slot2 || slot1 != slot3 || slot2 != slot3)
{
if (slot1 == slot2 && slot1 == slot3 && slot2 == slot3)
{
cout << "\tYou won " << fixed << setprecision(2) << credits * percent << " credits!\n";
credits += (credits * percent);
cout << "Continue (y/n)? ";
cin >> keepPlaying;
if (keepPlaying == 'y')
{
cout << "You have " << credits << " credits left.\n";
cout << "What percentage of credits do you want to bet(0-1)? ";
cin >> percent;
spin(slot1, slot2, slot3);
cout << "Slot value = " << slot1 << "-" << slot2 << "-" << slot3 << endl;
continue;
}
else if (keepPlaying == 'n')
{
cout << "You are leaving with " << credits << " credits." << endl;
return 0;
}
}
else
{
cout << "\tSorry, you lost " << fixed << setprecision(2) << credits * percent << " credits." << endl;
credits -= (credits * percent);
cout << "Continue (y/n)? ";
cin >> keepPlaying;
if (keepPlaying == 'y' && credits != 0)
{
cout << "You have " << credits << " credits left.\n";
cout << "What percentage of credits do you want to bet(0-1)? ";
cin >> percent;
spin(slot1, slot2, slot3);
cout << "Slot value = " << slot1 << "-" << slot2 << "-" << slot3 << endl;
continue;
}
else if (keepPlaying == 'y' && credits == 0)
{
cout << "Get out of here bum!" << endl;
return 0;
}
else if (keepPlaying == 'n')
{
cout << "You are leaving with " << fixed << setprecision(2) << credits << " credits." << endl;
return 0;
}
}
}
return 0;
}`
Give this a try:
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
/* Start: Do Not Change */
const int MAX = 5;
const int MIN = 1;
// This function takes tree ints as parameters
// and sets them to a random number
void spin(int & n1, int & n2, int & n3)
{
n1 = rand()%(MAX-MIN)+MIN;
n2 = rand()%(MAX-MIN)+MIN;
n3 = rand()%(MAX-MIN)+MIN;
}
/* End: Do Not Change */
// How many credits the user has to play with
double credits = 1000.00; // 1000 is the starting point
void doGame(){
int slot1, slot2, slot3;
double percent;
double dCreditsWagered;
cout << "What percentage of credits do you want to bet(0-1)? ";
cin >> percent;
dCreditsWagered = credits*percent;
spin(slot1, slot2, slot3); // At this point slot1-3 all have a random value between 1 and 5
//spin function
cout << "Slot value = " << slot1 << "-" << slot2 << "-" << slot3 << endl;
// Check if all slots are equal:
if( (slot1 == slot2) && (slot1 == slot3)){
// User won!
cout << "\tYou won " << fixed << setprecision(2) << dCreditsWagered << " credits!" << endl;
credits += dCreditsWagered;
} else {
// User lost :(
cout << "\tSorry, you lost " << fixed << setprecision(2) << dCreditsWagered << " credits." << endl;
credits -= dCreditsWagered;
}
}
int main(){
char keepPlaying;
srand (time(NULL));
cout << "Welcome to the slots, you have 1,000.00 credits." << endl;
do{
doGame();
cout << "Continue (y/n)? ";
cin >> keepPlaying;
if (keepPlaying == 'y' && credits > 0) {
// User would like to play another round
cout << "You have " << credits << " credits left." << endl;
} else if(keepPlaying=='y' && credits <= 0){ // credits should never be < 0, but hey, doesn't hurt to check, right?
// User does not have enough credits to continue playing:
cout << "Get out of here you bum!" << endl;
break;
}else if (keepPlaying == 'n') {
// User would like to quit
cout << "You are leaving with " << credits << " credits." << endl;
break;
}
}while(true);
return 0;
}
I moved your actual game logic to a function called doGame(). When ran, the game enters an infinite do-while loop which executes doGame() and then checks if the user wants to continue playing. If the user wants to continue playing and they still have credits left, the loop will restart (and thus doGame() will be called again.) If the user chooses to quit or if the user is out of credits and they try to play again, the code will break out of the do-while loop.
I have not tested this code yet, so if you find an error, please let me know so I can fix it.
Edit: Just compiled and tested. I found two errors. #1, your int spin(int &n1, int &n2, int &n3) function is declared to return an int, but it does not return anything. #2, I was missing a semicolon after }while(true) (syntax error).
Aside from those two errors, the code seems to perform as expected. Ideally, one should add a function called bool keepPlaying() which would prompt the user to continue playing and then validate that the user's input was either y or n (and prompt them again if it they entered anything else), but I will leave that up to you :P
Generally when you want an infinite loop, you use while (true) and then break on the condition that breaks the loop.
For example,
while (true) {
...
if (credits < .01) {
cout << "Get out of here bum!" << endl;
break;
}
...
if (keepPlaying == 'n')
break;
}
Note, I compared the credit value against a larger value than zero. The way floating point values work, you normally can't compare for equality. This is because they have limited precision (float, double, etc...) and they use a base other than base10 (base2).
You generally can't compute exact values like zero by adding, subtracting, multiplying or dividing. A number of values can't be represented exactly using base2 floating point as well (actually this includes .01).
Try the while loop code below, you may want to give user a choice to end the game. User can end the game if they input Ctrl+Z
(Linux) or Ctrl+d (Windows):
cout << "Welcome to the slots, you have 1,000.00 credits.\n"
<< "What percentage of credits do you want to bet(0-1)? Use EOF to end the game";
while(std::cin >> percent) {
spin(slot1, slot2, slot3); // At this point slot1-3 all have a random value between 1 and 5
//spin function
cout << "Slot value = " << slot1 << "-" << slot2 << "-" << slot3 << endl;
if (allSlotMatchs) {
}
else {
}
}
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;