I am trying to keep a track of total amount of bought groceries.
In my program, every time I buy apples, cheese, or bread, the program should continue with displaying the menu again.
But it keeps asking "How many apples?" after the program has already calculated the total for the apples instead of going back to the menu to choose another item.
Perhaps it has something to do with the type of loop I have used.
I am stuck on trying to figure this out. Any help would be appreciated.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
double BUDGET;
const double apple= .60;
const double lb_cheese= 1.60;
const double loaf_bread = 2.50;
double total;
int count;
char choice;
double amount_left;
cout <<"Welcome! What is the budget for your picnic lunch?"<< endl;
cin>> BUDGET;
cout<<"Choose one of the following"<<endl;
cout<<"-------------------------------------"<<endl;
cout<<" MENU \n "<<endl;
cout<<"A-Apple B-Cheese C-Bread"<<endl;
cout<<" $0.60 $1.50 $2.50 "<<endl;
cout<<"-------------------------------------"<<endl;
cin>> choice;
while ((choice != 'Q') && (total <BUDGET)) //Q is the sentinel value to "quit" the program
{
switch(choice)
{
case 'A':
case 'a':
cout<<"How many apples?";
cin>> count;
total+= (count *apple);
break;
case 'B':
case 'b':
cout<<"How many pounds of cheese ?";
cin>> count;
total+= (count* lb_cheese);
break;
case 'C':
case 'c':
cout<<"How many loafs of bread?";
cin>> count;
total+= (count * loaf_bread);
break;
default:
cout<<"The entry you have entered is not valid, please try again."<<endl;
}
if( total > BUDGET)
{ cout<<"You have exceeded your budget please check your cart.\n\n";
break;
}
cout<<"Your total is: $"<<setprecision((2))<<fixed<<total<<endl;
amount_left= BUDGET-total;
cout<<"You have $"<<setprecision(2)<<fixed<<amount_left<<" left to spend."<<endl;
}
return 0;
}
Displaying menu is out of the loop:
display menu
read option
while (option != quit) {
do some calculations
}
and the menu is therefore displayed only once. You could change it to infinite loop:
while (true) {
display menu
read option
if (choice == 'Q' || total >= BUDGET)
break;
do some calculations
}
Also try to avoid writing functions that are longer than 50 lines, place some logic into some different function and just call this function, decompose it to smaller parts, it will be much easier to read and also much easier to understand.
Yes, get the menu in a loop to display it the number of times you desire and also please remember to initialize your variables as good practice.
Double total=0.00 // initialize.
Related
I am new at c++ and for an assignment I have a program that requires a switch within a while but i keep getting stuck in an infinite loop
I have tried looking up ways to solve it but since i am not skilled at c++, it is really hard for me to get my error
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void)
{
float length, width, perimeter, area;
char ans;
cout<<"Please enter the length of the rectangle: \n";
cin>>length;
cout<<"Please enter the width of the rectangle: \n";
cin>>width;
cout<<"What do you wish to do with these values?\n";
cout<<"Choose an option from the menu: \n";
cout<<"1 - Calculate Perimeter\n";
cout<<"2 - Calculate Area\n";
cout<<"3 - Quit\n";
cout<<"Please enter your choice: \n";
cin>>ans;
while (ans != '3')
{
printf("give option: "); //found this online
ans = getchar(); //this too
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
}
printf("Program finished...\n"); //this was online too
return 0;
}
when i enter the option 2 or 1, there is an infinite loop and i cant seem to fix that.
I am not use to formatting on this site, please excuse the way i formatted my code
getchar() is not the right function to use there. It returns all characters, spaces, newlines, etc.
If you add a line to output the value of ans right after that, you will notice all the values that are assigned to ans.
ans = getchar();
cout << "ans: " << (int)ans << endl;
To skip whitespaces from the stream, use
cin >> ans;
In addition, the logic to get ans inside the while loop is flawed. It should be after the switch statement. Otherwise, your program tries to read ans twice before the first execution of the switch statement.
Here's an updated version of the relevant code that works for me.
cout << "Please enter your choice: \n";
cin >> ans;
while (ans != '3')
{
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
cout << "Please enter your choice: \n";
cin >> ans;
}
Here is some help regarding formatting : https://stackoverflow.com/editing-help.
Indent the entire code 4 spaces to the right for a code block.
You must also be able to see the preview below as you keep writing the question.
getchar() isn't the appropriate function to use here. Read about the nuance here : http://www.cplusplus.com/forum/general/193480/
cin will be more appropriate to use.
Also, analyse your code step by step. You have an input taking line outside the while loop, and one inside too. Realise why this is wrong and try fixing it.
Since this is an assignment question, I won't be telling you the answer, but hopefully lead you to understand where you are going wrong.
After you solve the problem, please go back and analyse why your original code did not work. It helps immensely.
I'm having problem with the string input, the program stops running whenever i enter a string and also if possible kindly fix my statements on the records because they don't seem to work well. Also, how do i delete a string? I tried to replace it with 'none' here for a sample. Thank you in advance!
Here is my code:
#include <iostream>
using namespace std;
int main(){
//Initializing
char choice;
int i, j, record=0, totalrecord;
int id[record];
string name[record];
double price[record];
bool back=true;
string none;
//Menu
while(back=true){
cout<<"*******************************"<<endl;
cout<<"[A] Add Record"<<endl;
cout<<"[V] View Record"<<endl;
cout<<"[E] Edit Record"<<endl;
cout<<"[D] Delete Record"<<endl;
cout<<"[L] View All Record"<<endl;
cout<<"Enter your choice and press return: "<<endl;
cin >> choice;
switch (choice){
//Add Record
case 'a':
case 'A':
record++;
cout<<"Input ID: ";
cin>>id[record];
cout<<"Input Name: ";
cin>>name[record];
cout<<"Input Price: ";
cin>>price[record];
break;
//View Record
case 'v':
case 'V':
cout<<"Enter ID you wish to view: ";
cin>>id[record];
cout<<"ID Name Price"<<endl;
cout<<id[record]<<" "<<name[record]<<" "<<price[record]<<endl;
break;
//Edit Record
case 'e':
case 'E':
cout << "Enter ID you wish to edit: ";
cin>>id[record];
cout<<"Input NEW name: ";
cin>>name[record];
cout<<"Input NEW price: ";
cin>>price[record];
break;
//Delete Record
case 'd':
case 'D':
cout << "Enter ID you wish to delete";
cin>>id[record];
id[record]=0;
name[record]=none;
price[record]=0;
break;
//View All Records
case 'l':
case 'L':
cout<<"ID Name Price"<<endl;
for(i=1; i<totalrecord+1; i++){
cout<<id[i]<<" "<<name[i]<<" "<<price[i]<<endl;
}
break;
//Exit Program if invalid input
default:
back=false;
break;
}
}
return 0;
}
Well, one problem is that here:
int i, j, record=0, totalrecord;
int id[record];
string name[record];
double price[record];
You are trying to create variable length arrays, which isn't supported in C++. Not only that, but even if it were supported you would be creating an array of size 0, since record = 0.
Thus, you need a compile-time constant value for the size of the array that isn't 0.
constexpr std::size_t RECORD_SIZE = 100; // make this any other that isn't less than or equal to 0
Then, you can create your array like this
int id[RECORD_SIZE];
string name[RECORD_SIZE];
double price[RECORD_SIZE];
However, one problem with this strategy is that if you want have an amount of records that exceed the RECORD_SIZE since you can't resize the array. Thus, I recommend that you see my final point.
Your logic when viewing, editing, and deleting a record is also incorrect since you always access an invalid index as the value of record will point to an empty slot so long as the array isn't full. Not only that, but there is no error checking.
Nonetheless, I assume you wanted to do those operations based on an index.
std::size_t index = 0;
std::cin >> index;
Then for the viewing and editing operations you would use that index to manipulate the records.
For the deleting operation, you would have to shift the records that are to the right of the deletion point left.
However, for these tasks I'd ultimately recommend that you use std::vector because it has support for all the operations you require and because it has a much greater dynamic capacity.
My teacher wanted me to make a program based on An Employee which includes -
His Name
His Id
His Sallary
and we needed to make this using - Structures & Functions & Array as we are not that good in C++ so we just make simple programs . the code of the program i made is below , [ http://pastebin.com/9UFFJseN ]
#include<iostream.h>
#include<conio.h>
#include<dos.h>
#include<process.h>
#include<stdio.h>
struct employee
{
char empname[40];
int empid,empsalary;
}; employee e1;
void add_record(void);
void display_record(void);
void search_record(void);
void welcome();
void exito();
void main()
{
clrscr();
int choice,id;
cout<<"Welcome to Employee Info Menu by Rohit Jalan \n\n\n";
cout<<"1 -> Add Record\n";
cout<<"2 -> Display Record\n";
cout<<"3 -> Search Record\n";
cout<<"4 -> Exit";
cout<<"\n\t\t --> ";
cin>>choice;
switch(choice)
{
case 1: add_record();break;
case 2: display_record();break;
case 3: search_record();break;
case 4: exito();
}
getch();
}
void add_record()
{
clrscr();
cout<<"You have pressed 1\n\n\n";
cout<<"Please enter employee name : ";
gets(e1.empname);
cout<<"Please enter the employee id : ";
cin>>e1.empid;
cout<<"Please enter the employee salary : ";
cin>>e1.empsalary;
cout<<" \n \n \n \n";
main();
}
void display_record()
{clrscr();
cout<<"\nEmployee Name is : ";
puts(e1.empname);
cout<<"\nEmployee ID is : ";
cout<<e1.empid;
cout<<"\nEmployee salary is : ";
cout<<e1.empsalary;
getch();
main();
}
void search_record()
{int id;
clrscr();
cout<<"Please enter the id of the employee\n: ";
cin>>id;
if(id==e1.empid)
{
display_record();
}
else cout<<"\nRecord not found...";
getch();
main();
}
void exito()
{clrscr();
cout<<"\n\n\n\n\t\t\t Thank you. ";
cout<<"\n\n\n\n\n\n\t\t\t Program by \n\n\n";
cout<<"\t\t\t";
delay(500);cout<<"ROHIT";
delay(500);cout<<" JALAN";
cout<<"\n\t\t\t";
delay(500);cout<<"Roll No";
delay(500);cout<<" 11436";
cout<<"\n\t\t\t";
delay(500);cout<<"Class";
delay(500);cout<<" XI-D";
delay(500);cout<<"....";
delay(100);
exit(0);
}
And now my teacher is asking me what if she wishes to enter more then 1 record of data and display more then 1 , or you can say she wants to decide that how much she wants to enter and display , as i am unable to solve her problem i request you all guys to help me in a simple and easy manner as i`m newbie out here . Please don't delay in answer i have a practical examination on 27th Feb 2015 . if you are unable to see my coding -
http://pastebin.com/9UFFJseN#
Thanks In Advance .
In order to perform actions more than once, you need a loop.
unsigned int Display_Menu(void)
{
unsigned int selection = 0;
while (selection != 4)
{
static const char menu_text[] =
"\n"
"Welcome to Employee Info Menu by Rohit Jalan \n\n\n"
"1 -> Add Record\n"
"2 -> Display Record\n"
"3 -> Search Record\n"
"4 -> Exit\n"
"\t\t --> ";
cout.write(menu_text, sizeof(menu_text) - 1);
cin >> selection;
if ((selection >= 1) && (selection <= 4))
{
break;
}
cout << "\nInvalid selection, try again.\n";
}
return selection;
}
The above function displays a menu and if the User enters an invalid choice, it will print the menu again. After a valid choice is received, the function returns to the caller.
This is an example of doing something more than once.
So if your instructor wants to perform more than one action, how would you do it?
Edit 1:
In general a Menu consists of two pieces: 1) Displaying the selections and 2) Processing the choices. The above code handles the displaying of the selections.
// Forward declarations
void Add_Record(void);
void Display_Record(void);
void Search_Record(void);
void Process_Choices(void)
{
unsigned int choice = 0;
do
{
choice = Display_Menu();
switch (choice)
{
case 1: Add_Record(); break;
case 2: Display_Record(); break;
case 3: Search_Record(); break;
}
} while (choice != 4);
}
The above function displays the menu, calls functions according to the User's selection and repeats. It ends when the User enters the number 4.
Again, notice the loop construct that is used for performing actions more than once.
whenever I enter a different case and enter an hour that meets the if statements requirements the else also gets printed, help I just need one output from each different situation.
the example below is the error I get.
ex: enter 'a' enter '11' output 'the amount due is 11.95' 'the amount due is 9.95'
//Libraries
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
//Global Constants
//Functioning Prototypes
//Execution Begins here
int main(int argc, char *argv[]){
//Declare Variables
char pack;
int hours;
float due;
//prompt user
cout<<"Please choose one monthly internet subscription package: a, b, or c\n";
cin>>pack;
cout<<"Enter how many hours were that month used\n";
cin>>hours;
//process
cout<<setprecision(2)<<fixed<<showpoint;
switch (pack){
case 'a':
if (hours>=10 && hours<=744){
hours=(hours-10)*2;
due=hours;
due+=9.95;
cout<<"The amount due is $"<<due<<endl;
}
else if (hours>=744){
cout<<"ERROR: a month cannot exceed 744 hours\n";
}
else ( hours<=10);{
due=9.95;
cout<<"The amount due is $"<<due<<endl;
}
break;
case 'b':
if (hours>20 && hours<744){
hours=(hours-20);
due=hours;
due+=14.95;
cout<<"The amount due is $"<<due<<endl;
}
else if (hours>=744){
cout<<"ERROR: a month cannot exceed 744 hours\n";
}
else (hours<=20);{
due=14.95;
cout<<"The amount due is $"<<due<<endl;
}
break;
case 'c':
if (hours>=744){
cout<<"ERROR: a month cannot exceed 744 hours\n";
}
else if (hours<744);{
due=19.95;
cout<<"The amount due is $"<<due<<endl;
}
break;
}
system("PAUSE");
return 0;
}
else (hours<=20);{
due=14.95;
cout<<"The amount due is $"<<due<<endl;
}
is equivalent to:
else (hours<=20) {
//Do nothing
}
{
due=14.95;
cout<<"The amount due is $"<<due<<endl;
}
You need to remove the ";". Otherwise, the last code block will always be executed because it isn't part of the else block.
So on my final project, a black jack and poker simulator using inheritance from a cards class, we have to keep track of the user's bet and total Money. However, in my code, it does very strange things. For example: if your total money was 1000000000 dollars and you bet 100 and won back 200 your new total money is now equal to 199 dollars
My program goes back and forth from doing this, and not doing this. It's maddening and I don't know why it's happening. The following is my main function, and my two functions that handle each poker game. If anyone thinks more code is needed to answer, though I'll gladly include class headers and implementation files. Thanks to all who may help! The following is my main functions, and the two functions to handle each game:
unsigned int handlePoker(unsigned int);
unsigned int handleBlackJack(unsigned int);
//main function:
//asks the user what game they want to play
//then calls a function for the appropriate
//game chosen
int main()
{//two choices:
//one for quitting the program
//the other for whichever game they want
char yesOrNo;
char choice;
unsigned int totalMoney;
cout<< "please enter a starting amount to bet with"<<endl;
cin>>totalMoney;
cout<<"would you like to play?"<<endl;
cout<<"enter 'y' for yes and 'n' for no"<<endl;
cin>>yesOrNo;
do{
//ask the user which game they want
cout<<"would you like to play poker or black jack?"<<endl;
cout<<"input '1' for poker and '0' for blackjack"<<endl;
cin>>choice;
if(choice == '1')
{
totalMoney = handlePoker(totalMoney);
}//end if
else if(choice == '0')
{
totalMoney = handleBlackJack(totalMoney);
}//end else if
else
{
cout<<"I'm sorry, the input you entered was invalid"<<endl;
cout<<"please try again"<<endl;
cin.clear();
}//end else
cout<<"would you like to try again?"<<endl;
cout<<"('y' for yes, or 'n' for no)"<<endl<<endl;
cin>>yesOrNo;
}while(yesOrNo == 'y' || yesOrNo == 'Y'); //end do while loop
return 0;
}//end int main
//handle poker:
//a void function which takes an
//unsigned integer value
//the function declares a "poker" object
//and uses it's void functions to sim a poker game
unsigned int handlePoker(unsigned int tot)
{
unsigned int multiply;
unsigned int betMonies;
unsigned int win;
poker round;
cout<<"how much do you want to bet?"<<endl;
cin>>betMonies;
//if the bet money entered was valid
// we begin playing
if(betMonies < tot)
{//big if begin
//ask if they want a better hand
round.betterHand();
//set the number we multiply your money by
multiply = round.rewardMoney();
//if multiply is 0
//then the user has lost this hand
//we inform them as such, and subtract
//their bet money from their total money
if(multiply == 0)
{
cout<<"I apologize, but you seem to have lost"<<endl;
cout<<"when you lose, your bet is subtracted"<<endl;
cout<<"your initial balance was: "<<tot<<endl;
//decrement the total
tot = (tot - betMonies);
cout<<"your new balance is: "<<tot<<endl;
}//end if
//if multiply is not 0 (assuming it's not negative
//because there's no way it could be)
//we tell them what they've won, and add it to
//their total money
else
{
win = (multiply*betMonies);
cout<<"your initial balance was: "<<tot<<endl;
cout<<"your win was"<<win<<endl;
//increment the total
tot = (win + tot);
cout<<"your new balance is "<<tot<<endl;
}//end else
}//big if end
//if the amount entered was not valid
//simply tell them, then run the loop again
else
{//else begin
cout<<"I'm sorry, that was not a valid amount of money"<<endl;
cout<<"please try again"<<endl;
}//end else
round.shuffleDeck();
return tot;
}//end handlePoker
//handle Black jack:
//a function returning an unsigned int
//that keeps track of the total money
//declares a black jack object
//and uses it's member functions to play black jack
unsigned int handleBlackJack(unsigned int tot)
{
blackJack play;
unsigned int reward;
unsigned int betMoolah;
//ask the user for the bet they want
cout<<"how much do you want to bet?"<<endl;
cin>>betMoolah;
//if the bet is less than the total passed by reference
//then we can start running the game
if(betMoolah < tot)
{
//print the hands dealt in the constructor
play.printHands();
//run the function that lets them hit or stay
//the function contains a do while loop
// so, no looping is required
play.hitOrStay();
//we then handle the reward
//which returns an integer type
reward = play.handleReward(betMoolah);
//prints dealer and player's hands fully
play.printHandGame();
//in one of the cases, reward is set to -1
//we use this here:
if(reward < 0 )
{
//if the reward is negative, then
//we subtract the bet money
//then we tell the user their new balance
cout<<"your balance was "<<tot<<endl;
cout<<"you have lost, so your bet is subtracted"<<endl;
tot = (tot-betMoolah);
cout<<"your new balance is: "<<tot<<endl;
}//end if
//if the reward is above 0, then we add the reward to the total
else if(reward > 0)
{
cout<<"your original balance was "<<tot<<endl;
cout<<"your winnings are: "<< reward<<endl;
tot = reward + tot;
cout<<"your new balance is: "<<tot<<endl;
}//end else
else
{
cout<<"you have lost no money"<<endl;
cout<<"your balance is still " <<tot<<endl;
}
}//end of the big if
//if the amount of money entered is above total money
//then the money entered isn't valid at all
else
{
cout<<"the amount of money you've entered is not valid"<<endl;
cout<<"please try again"<<endl;
}// end else
play.shuffleDeck();
return tot;
}//end handleBlackJack
I can't fully explain what your seeing, but I did notice a liberal use of unsigned int. In particular, in handleBlackJack you have:
unsigned int reward;
and then
reward = play.handleReward(betMoolah);
and finally
if(reward < 0 )
If reward can be negative, it shouldn't be an unsigned int. As others have suggested, step through it in a debugger and "follow the money".