I can't select a different option in my program - c++

I was writing a program inspired by one of my favorite books Diary of a wimpy kid. You play as Greg's dad and you have 3 options with what to do with him. When i ran the program I first selected the first option which printed the first one. I tried it again with the third option as well with the same result.
#include <iostream>
using namespace std;
void greg(int choice){
cout<<"Option 1: Scold."<<endl;
cout<<"Option 2: Take away games."<<endl;
cout<<"Option 3: kill "<<endl;
cin>>choice;
//Options on what to do with greg and getting user input.
if(choice = '1'){
cout<<"You told Greg he sucks. Responds with:"<<endl;
cout<<"Ok.."<<endl;
} else if(choice = '2'){
cout<<"You storm into Greg's room while Greg keeps asking you why."<<endl;
cout<<"Once you are insde and grab his game."<<endl;
}else if(choice = '3'){
cout<<"you killed greg."<<endl;
cout<<"A white bang then proceeds to happen."<<endl;
cout<<"You killed the main character. You no longer exist."<<endl;
}else{
cout<<"no"<<endl;
}
}
//All above is what will happen if you pick a choice.
int main()
{
cout<<"There once was a guy named Frank."<<endl;
cout<<"You talk to greg."<<endl;
cout<<"Yeah dad?"<<endl;
greg(3);
return 0;
}

you have to use a double = because you want to compare the values in the if statement. You dont want to set the left variable equal to the right value.
2.because youre passing a int value into the function, the program will not return true because a int is not equal to a string. So you dont have to use these '' around the number.
In conclusion you have to change this:
...
if(choice == 1){
//your code
}
else if(choice == 2){
//your code
}
else if(choice == 3){
//your code
}
...

Related

Yes/No always pick the first option (C++) [duplicate]

This question already has answers here:
Test for multiple conditions in same if test?
(3 answers)
Closed 5 years ago.
I'm really new in C++. Currently helping my sister about this. I'm making a standard restaurant cashier program, with a little code to count the change money. At the end i would like to ask whether the user may continue or exit. I am using goto statement, if the user press Y it will go back, and if user press N it will exit.
My problem is the code only accept the first (go back) option. So if I press N the program won't exit. Can you please help me? Here are my code at the end:
cout<<"again?";
cin>>response;
if (response == 'Y') {
goto a;
}
else if (response == 'N') {
exit(0);
}
edit 1
cout<<"\nAgain?";
cin>>response;
if (response == 'Y'||'y'){
main();
}
else if (response == 'N'||'n'){
exit(0);
}
edit 1
changed the code so when the user press Y it will go back to the top. how do you exit the loop if using this snippet?
cout<<"\nMasukan Jumlah Pembelian Untuk Menu A : "; //input for Menu A and B quantities
cin>>jml_menu_A;
hrg_menu1=menu_A*jml_menu_A; //calculation
cout<<"\nTotal Harga untuk Menu A : "<<menu_A<<" * "<<jml_menu_A<<" = Rp "<<hrg_menu1<<",00\n";
cout<<"\nMasukan Jumlah Pembelian Untuk Menu B : ";
cin>>jml_menu_B;
hrg_menu2=menu_B*jml_menu_B; //calculation
cout<<"\nTotal Harga untuk Menu B : "<<menu_B<<" * "<<jml_menu_B<<" = Rp "<<hrg_menu2<<",00\n";
ttal_bayar=ttal_hrg_menu_A+ttal_hrg_menu_B;
cout<<"\nMaka yang Harus Dibayarkan : "<<ttal_hrg_menu_A<<"+"<<ttal_hrg_menu_B<<"= Rp "<<ttal_bayar<<",00\n"; // total payment
//Bayar;
cout<<"\nMasukan Uang untuk pembayaran : ";
cin>>uang;
kembalian=uang-ttal_bayar; //total payment
{
if (uang>=ttal_bayar){ // change if the money is more
kembalian=uang-ttal_bayar;
cout<<"\nKembaliannya adalah..."<<kembalian<<" Rupiah..";
}
else if (uang<ttal_bayar){ // if the payment is less
kembalian=uang-ttal_bayar;
cout<<"\nMaaf Kembalian Anda Kurang";
}
}
cout<<"\nApakah ada transaksi lain?"; // confirm to start all over, or exit the program
cin>>response;
if (response == 'Y'||'y'){
main();
}
else if (response == 'N'||'n'){
exit(0);
}
}
edit 2: added the expected input and output
Something like this?
char foo;
while(true)
{
cout<<"again? ";
cin<<foo;
if(foo == 'N' || foo =='n')
break;
else
{
//Do important stuff
}
}
if (response == 'Y'||'y'){
This statement will always be true, make it:
if (response == 'Y'||response == 'y'){

I dont know why i cant loop the whole code? when i press y on "next customer" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to loop the whole codes If I press Y on "next customer"? and to reset the program just like the first try. Just type 0101 and 0307 on itemcode i put only some of my codes. define gotoxy is running only do while on "next customer " I think is the error?
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#define g gotoxy
main()
{
char back_, back;
float change, p0101 = 25.5, p0307=11,subtotal=0,total=0;
int y=9, quantity, itemcode, cash,discount;
clrscr();
do{
do{
g(1,8);
cout<<"Itemcode";
g(15,8);
cout<<"Quantity";
g(41,8);
cout<<"Price";
g(51,8);
cout<<"Subtotal";
g(62,8);
cout<<"Total";
g(1,y);
cin>>itemcode;
g(15,y);
cin>>quantity;
{
g(25,y);
if (itemcode == 0101){
cout<<"Yogurt(12 oz)";
subtotal = quantity * p0101;
}
else if (itemcode == 0307){
cout<<"Pumpkin (1000g)";
subtotal = quantity * p0307;
}
}
{
g(41,y);
if(itemcode == 0101){
cout<<"25.50";
}
else if (itemcode == 0307){
cout<<"79.75";
}
}
g(51,y);
cout<<subtotal;
total=total+subtotal;
g(62,y);
cout<<total;
subtotal=0;
g(72,8);
cout<<"Add item?";
g(72,y);
cin>>back;
y++;
if(back=='n'||back=='N'){
{
g(1,y+2);
cout<<"CASH: ";
cin>>cash;
}
if(cash>total){
{
g(1,y+3);
cout<<"[R]-REGULAR\t[D] - WITH DISCOUNT :";
}
cin>>discount;
g(1,y+4);
if(discount=='d'||discount=='D'){
(change=cash-(.8*total));
cout<<"Change: "<<change;
}
else{
change=cash-total;
cout<<"Change: "<<change;
}
}
else if(cash<total){
cout<<"Insufficient amount";
}
{
g(18,y+8);
cout<<"EXCHANGE OF ITEM TO ANOTHER TYPE AND SIZE IS ALLOWED,";
}
{
g(18,y+9);
cout<<"SUBJECT TO STANDARD PROVISIONS AND PRODUCT WARRANTY";
}
{
g(18,y+10);
cout<<" PLEASE PRESENT THIS RECEIPT";
}
{
g(15,y+12);
cout<<"Next Customer?";
cin>>back;
}
}
} while(back_=='Y'||back_=='y');
} while(back=='Y'||back=='y');
enter code here
getchar();
return 0;
}
You have some mistakes in programs.
take discount type int but use as a char
When your takes a integer value and after that takes a char, then between these, need to use getchar() because at the time of getting the integer, you press enter, so need to read it.
When you read a char, check that did you take a input before it, if takes, then read the newline character by getchar()
Check the code
#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
int main()
{
char newCustomer, addItem,discount;
float change, p0101 = 25.5, p0307=11,subtotal=0,total=0;
int y=9, quantity, itemcode, cash;
do{
subtotal=0,total=0;
do{
cout<<"Itemcode: ";
cin>>itemcode;
cout<<"Quantity: ";
cin>>quantity;
{
if (itemcode == 101){cout<<"Yogurt(12 oz)";
subtotal = quantity * p0101;
}else if (itemcode == 307){cout<<"Pumpkin (1000g)";
subtotal = quantity * p0307;
}}
{
cout<<"Price: ";
if(itemcode == 101){
cout<<"25.50\n";
}else if (itemcode == 307){
cout<<"79.75\n";
}}
cout<<"Subtotal: ";
cout<<subtotal<<"\n";
total=total+subtotal;
cout<<"Total: ";
cout<<total<<"\n";
subtotal=0;
cout<<"Add item?";
cin>>addItem;
getchar();
if(addItem=='n'||addItem=='N'){
{
cout<<"CASH: ";
cin>>cash;}
getchar();
if(cash>total){
{
cout<<"[R]-REGULAR\t[D] - WITH DISCOUNT :";}
cin>>discount;
char c = getchar();
if(discount=='d'||discount=='D'){(change=cash-(.8*total));
cout<<"Change: "<<change<<"\n";}
else{change=cash-total;cout<<"Change: "<<change;}
}
else if(cash<total)
{cout<<"Insufficient amount";}
{
cout<<"EXCHANGE OF ITEM TO ANOTHER TYPE AND SIZE IS ALLOWED,";
}
{
cout<<"SUBJECT TO STANDARD PROVISIONS AND PRODUCT WARRANTY";}
{
cout<<" PLEASE PRESENT THIS RECEIPT\n";} {
cout<<"Next Customer?";cin>>newCustomer;char c = getchar();}
}
}while(addItem=='Y'||addItem=='y');
}while(newCustomer=='Y'||newCustomer=='y');
return 0;
}
I cannot see where you input into back_ but you have cin>>back; twice. Could this be your error? Your control structures are hard to follow.
You have, essentially,
do {
do {
// input some stuff for an item
cout<<"Add item?";
cin>>back;
if(back == 'n' || back == 'N')
{
// some code to finalize the transaction
cout<<"Next Customer?";
cin>>back;
}
} while (back_=='y' || back_=='Y')
} while (back=='y' || back == 'Y')
You defined back_ but never initialized it or used it in your code so when while (back_=='y' || back_=='Y') comes along, even when you press 'y', the loop never loops.
If you were to change the code to:
do {
do {
// input some stuff for an item
cout<<"Add item?";
cin>>back;
if(back == 'n' || back == 'N')
{
// some code to finalize the transaction
cout<<"Next Customer?";
cin>>back_;
}
} while (back_=='y' || back_=='Y')
} while (back=='y' || back == 'Y')
The program would certainly loop again if you pressed 'y' but you would get some interesting behavior when you pressed 'n' for "Add item?" and 'y' for "Next Customer?". I predict the program will close prematurely. Better to have:
char new_customer, add_item
do {
//---This is the outer loop---//
do {
//---This is the inner loop---//
// input some stuff for an item
cout<<"Add another item?";
cin>>add_item;
if(add_item == 'n' || add_item == 'N')
{
// some code to finalize the transaction
cout<<"Next Customer?";
cin>>new_customer;
}
//---End of the inner loop---//
} while (add_item=='y' || add_item=='Y')
//---End of the outer loop---//
} while (new_customer=='y' || new_customer=='Y')
This way the inner loop breaks when you press 'n' at "Add Item?" and the outer loop breaks when you press 'n' at "Next Customer?", effectively ending the program. Pressing 'y' at either will continue their respective loops.
Other odd behavior can come from
Pressing anything other than 'y' or 'n' at decision points
Inputting anything other than numbers into variables that are used to calculate prices and the such
Not formatting your output into the price fields with $ or having two decimal places for money
The first two can be fixed by reading everything in as strings and then parsing it out character by character to check for valid input and then converting the appropriate strings into a numbers using built-in C++ functions. The last one can be fixed with a little fancy calculations on the data with the % (modulus) operator to see if the values end with a zero or not. Just some ideas.
Looks like it mostly works, except for that one major error.

Multiple if-else in C++

I am getting confused with a simple program of multiple if-else in c++. The code
is given below.
include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
if(i==1)
{
cout<<"Sunday";
}
if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}
When I try to run this code ,the output shows this.
Enter the number:1
Sunday invalid key
So my question is why the output executing the Else part though the output is True..? Please help me . Thank You
This is because you don't have "multiple if-else", really. You have a single if (without else), then another if. The two are independent. You probably wanted:
if(i==1)
{
cout<<"Sunday";
}
else if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
This makes sure the final else block only runs if none of the preceding conditions are met.
First you check whether i equals one. If it is the case, "Sunday" is printed. The if statement is finished at that point. Afterwards you check (in a separate if statetement) whether i equals two, you print "Monday" if it is the case, or "invalid input" if it is not the case. To obtain the result you want, write
else if (i == 2)
to have the second if/else statement only executed if i is not 1.
Alternatively, you might want to use a switch statement.
switch(i)
{
case 1:
cout << "Sunday";
break;
case 2:
cout << "Monday";
break;
default:
cout << "invalid input";
break;
}
But don't forget the breaks if using switch!
You have to put else if, if you wanna have the right processing:
if(i==1)
cout<<"Sunday";
else if(i==2)
cout<<"Monday";
else
cout<<" invalid input";
With else if, the second and the third condition are not processed, because the first one is alredy valid. In your code, it is first processed the code under the first condition, than because the input is not equal to 2, the code under the else is processed.
There are several bugs in this code. I explained and fixed it here-
#include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
cin >> i; //take the input number from the user
if(i==1)
{
cout<<"Sunday";
}
/* the i==1 and i==2 block will run separately unless you connect them with an else */
else if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}
This is cause you have used two branching statement for same input
1. The first if() statement check if your value is equal 1 or not
if(i == 1)
std::cout << "Sunday"; // here you have print "Sunday for 1
2. Then again you check your value with another if-else statement
if(i == 2)
std::cout << "Mondey";
else
std::cout << "invalid input"; // here you have print "invalid input"
//since i is not equal to 1
You have two different conditions. One is:
if(i==1) {
cout<<"Sunday";
} // this statement ends here.
The other:
if(i==2) {
cout<<"Monday";
} else {
cout<<" invalid input";
}
The second is always going to result " invalid input" when i is not 2.

How to end a loop early if a user says to C++

Note: This is a homework assignment.
I am trying to make a program that plays the game Pig! Pig is a game with the following rules:
1. First to get 100 GAME POINTS is the victor.
2. On your turn, you roll a dice. If you get a 1 at any roll, you end your turn and add 0 to your GAME SCORE.
3. If you roll any value other than a 1, you have the option to HOLD or PLAY. If you PLAY, your roll is added to your TURN SCORE and you roll again. If you HOLD, your TURN SCORE is added to your GAME SCORE and the turn passes to the computer.
The game is coming along very easily until I get to the following problem (see code):
int player(){
char PlayAgain = 'Y';
int turn_score = 0;
while (PlayAgain != 'N' || PlayAgain != 'n'){
int dice;
srand(time(NULL));
dice = rand() % 6 + 1;
turn_score = turn_score + dice;
if (dice != 1){
cout << "You rolled a " << dice << "! Would you like to roll again? [Y/N]: ";
cin >> PlayAgain;
if (PlayAgain == 'N' || PlayAgain == 'n'){
/*END TURN AND return turn_score;*/
}
}
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
system("PAUSE");
/*END TURN, NO SCORE ADDED*/
}
}
}
How can I have the program end the loop prematurely (if either the play HOLDS or dice == 1) and return the proper value (if HOLD, return turn_score. Else return 0)? [See two noted sections]
You can use break to get out of a loop. Since you're saying that you want to return "the right value" then you should do something like that:
On the first if clause
if (PlayAgain == 'N' || PlayAgain == 'n'){
/**Game-Specific logic here**/
return turn_score
}
and on the second one:
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
/**Game-Specific logic here**/
cin.get();
return turn_score;
}
A return statement doesn't need to be at the end of the function and more than one return statements can co-exist inside the same function
Rather then correcting your code I would like to make you clear about what actually is needed here.
Ever heard of break; statement.Let us understand with a simple example
see the following code snippet where your program is taking input from the user,it keeps on taking input from the user until you press 'A'
char var;
while(true)
{
cin>>var;
if(var=='A') break;
}
Now in this program,the while loop is set to true and will keep on running and taking input from the user,and the if statement will not run until the user have entered 'A'. AND the moment 'A' is given as the input,break will take the control out of the while loop for you.
How about having your 'return' statement (with the proper value depending on the case) inside your loop? This will break both the loop and the function, but returning the value you needed.

Simple program - menu is being displayed only once

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.