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

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'){

Related

I can't select a different option in my program

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
}
...

I need help on this C++ yes/no problem while using logical operators

So the problem is: Write a program that prints the question "Do you wish to continue?" and reads the input. If the user input is "Y", "Yes", "YES", then print out "Continuing". If the user input is "N" or "No", "NO" then print out "Quit". Otherwise, print "Bad Input". Use logical operators.
So far this is all the code that I have written. I know that it is not complete, and I do not know what else I need to add to the code.
#include <iostream>
using namespace std;
int main() {
char response;
cout << "Do you wish to continue?" ;
cin >> response;
if (response == 'Y'){
cout << "Continuing";
}
else if (response == 'N'){
cout << "Quit";
}
else if (response != 'N' || 'Y'){
cout << "Bad input";
}
return 0;
}
Update: so I edited my code and it is still giving me a bunch of errors. It's making me frustrated lol. Keep in mind I'm a beginner and we haven't learned loops yet. Sorry for the headache!
#include <iostream>
#include <string>
using namespace std;
int main() {
char response;
string help;
cout << "Do you wish to continue?" ;
cin >> response, help;
if (response == 'Y' || help == "Yes" || help == "YES"){
cout << "Continuing";
}
else if (response == 'N' || help == "No" || help == "NO"){
cout << "Quit";
}
else if (response != 'N' || response != 'Y' || help != "Yes" || help != "YES" || help != "No" || help != "NO"){
cout << "Bad input";
}
return 0;
}
First off I think this is a great start. Sounds like you are new to C++ so here are some suggestions:
1) Your response variable can only contain a character. I would suggest including string and changing the response to take a string from the user for 'Y', "Yes", etc.
2) I suggest wrapping your code in a while loop with an exit condition.
3) Each of your logic branches should include a return integer. This will give the program an exit condition if the logical conditions are met.
I know I haven't given you the answers fully. If you are truly stuck, reply back and we can walk through.
A simple way is to simply convert the user's answer to uppercase or lowercase. By doing this, you can simply use the lower case.
For your loop, you could for example use a "do..while".
#include <iostream>
#include <string>
using namespace std;
int main() {
int stop = 0;
string response;
//Continue until the user choose to stop.
do{
//-------------
// Execute your program
//-------------
cout << "Do you wish to continue? ";
cin >> response;
//-------------
//Convert to lower case
for (string::size_type i=0; i < response.length(); ++i){
response[i] = tolower(response[i]);
}
//-------------
//Check the answer of the user.
if (response.compare("y") == 0 || response.compare("yes") == 0){
cout << "Continuing \n";
}
else if (response.compare("n") == 0 || response.compare("no") == 0){
cout << "Quit \n";
stop = 1;
}
else{
cout << "Bad input \n";
}
}while(stop == 0);
return 0;
}
Like you said in the question, we care about Y,Yes,YES,N,No and NO. For anything else we need to print "Bad Input". Think about how you'd be storing these responses (hint: Sam Varshavchik's answer).
Once you've taken care of extracting user input, you'd want to check what the user actually entered and proceed accordingly. From your question it seems "if else" would do. You need to change the conditionals for your "if else ifs" because
you have 3 conditions for one type of response: Y, Yes and YES need one output - "continuing" while N, No and NO require a different output - "Quit" and for all others we print "Bad input". Think about what your conditionals should be and your if statement should look something like:
if (response == "Y" || response == "Yes" || response == "YES")
and then handle the case accordingly. You'd want to do the same for your No conditions and finally handle the case for all others. I'd suggest having your code like so:
if( conditionals for Yes){
//Code for Yes input
}
else if( conditionals for No){
//Code for No input
}
else{
//Code for all other inputs
}
It is tempting to give you the full answer but think about how your program needs to flow and proceed from there, you've almost got it!
If you have more questions post here and we'd be glad to help!

Running a simple C++ function

I've just started learning the basics in C++ and currently am trying to make a program that does a few basic things. The problem I have is occurring in the pasted function below.
At this point it literally does nothing when it runs. All I'm trying to do it make it so the function runs over and over again forever, until the user enters the letter 'q'.
The function must keep running even if the user enters some random string, anything, 'q' is the only keystroke that should stop the loop.
I have tried toying around with 'cin.whatever" and haven't found success. If you have an answer please provide as much explanation as possible. Thank you!
void menu()
{
cin.clear();
cin.ignore();
char quit = 'w';
while (quit != 'q') // while loop to allow the user infinite tries
{
cout << "Which story would you like to play? Enter the number of the story (1, 2, or 3) or type q to quit: " << endl;
cin >> quit;
if (quit < '1' or quit > '3') // make sure the user picks a valid choice
{
cout << "Valid choice not selected." << endl;
}
if (quit == '1')
{
story1(); // run story 1
}
if (quit == '2')
{
story2(); // run story 2
}
if (quit == '3')
{
story3(); // run story 3
}
if (quit == 'q')
{
cout << "good bye" << endl;
break;
}
}
}
Try adding single quotes around your 1,2,3 like you did with the q. The cin is expecting a char to be entered so evaluate it as such. e.g: if (quit == '1')

How to make my program loop back to the beginning based on user input?

I am trying to create a repetition structure for when I type 'Y' at the end of the code to rerun the "insurance price check" again.
#include <iostream>
using namespace std;
int main() {
// Declaration of variables
char animal, status, continue_;
int i=0;
//Begin Loop
cout<<"Welcome to the Animal Insurance Company! What type of animal would you like to insure today: Enter D for Dog, C for Cat, B for Bird or R for Reptile: "<<endl;
cin>>animal;
if(animal=='D' || animal=='d') {
cout<<"You have selected a dog, has your dog been neutered? Enter Y for Yes or N for NO."<<endl;
cin>>status;
if(status=='Y' || status=='y')
cout<<"The insurance for your dog cost is $50."<<endl;
else if(status =='N' || status=='n')
cout<<"The insurance for your dog cost is $80."<<endl;
else
cout<<"Invalid Input, please type Y or N"<<endl;
}
else if (animal=='C' || animal=='c') {
cout<<"You have selected a cat, has your cat been neutered? Enter Y for Yes or N for NO."<<endl;
cin>>status;
if(status=='Y' || status=='y')
cout<<"The insurance for your cat cost is $40."<<endl;
else if(status =='N' || status=='n')
cout<<"The insurance for your cat cost is $60."<<endl;
else
cout<<"Invalid Input, please type Y or N"<<endl;
}
else if (animal=='B' || animal=='b' || animal=='R' || animal=='r')
cout<<"The insurance cost will be $10"<<endl;
else
cout<<"Invalid Input"<<endl;
cout<<"Do you want to insure another animal? Enter Y for Yes or N for NO."<<endl;
cin>>continue_;
if(continue_=='n' || continue_=='N')
cout<<"Thank you for using Animal Insurance Company"<<endl;
return 0;
}
How do I make the code loop back to the beginning?
I'd recommend you use a do while loop. https://www.tutorialspoint.com/cplusplus/cpp_do_while_loop.htm
do
{
// begin loop
...
}while(continue_!='n' && continue_!='N');
Well for starters you would need a loop...
In this example, probably a while loop (pre-test if you are interested in looking it up)
To achieve what you want, you would need a boolean flag, and would run the loop as long as the flag is set to true.
(Assuming that the rest of your code works fine)
// Declaration of variables
char animal, status, continue_;
int i=0;
bool running = true;
//Begin Loop
while (running == true) {
// Rest of program
cout<<"Do you want to insure another animal? Enter Y for Yes or N for NO."<<endl;
cin>>continue_;
if(continue_=='n' || continue_=='N') {
cout<<"Thank you for using Animal Insurance Company"<<endl;
running = false;
}
}
return 0;
}
B. Ward is right, you have to use "nested" do-while loops to fully solve your problem. Because there are other conditions inside your code that needs to be met before program can proceed and they will also require the services of the do-while loop. Like this;
#include <iostream>
using namespace std;
int main() {
// Declaration of variables
char animal, status, continue_;
int i=0;
//Begin Loop
do {
cout<<"Welcome to the Animal Insurance Company! What type of animal would you like to insure today: Enter D for Dog, C for Cat, B for Bird or R for Reptile: "<<endl;
cin >> animal;
if(animal=='D' || animal=='d') {
cout<<"You have selected a dog, has your dog been neutered? Enter Y for Yes or N for NO."<<endl;
//until the required input is entered, program will keep asking for it
do {
cin>>status;
if(status=='Y' || status=='y') {
cout<<"The insurance for your dog cost is $50."<<endl;
break;
}
else if(status =='N' || status=='n') {
cout<<"The insurance for your dog cost is $80."<<endl;
break;
}
else {
cout<<"Invalid Input, please type Y or N"<<endl;
}
}while(status != 'y' || status != 'Y' || status != 'n' || status != 'N');
}
else if (animal=='C' || animal=='c') {
cout<<"You have selected a cat, has your cat been neutered? Enter Y for Yes or N for NO."<<endl;
//until the required input is entered, program will keep asking for it
do {
cin>>status;
if(status=='Y' || status=='y') {
cout<<"The insurance for your dog cost is $40."<<endl;
break;
}
else if(status =='N' || status=='n') {
cout<<"The insurance for your dog cost is $60."<<endl;
break;
}
else {
cout<<"Invalid Input, please type Y or N"<<endl;
}
}while(status != 'y' || status != 'Y' || status != 'n' || status != 'N');
}
else if (animal=='B' || animal=='b' || animal=='R' || animal=='r')
cout<<"The insurance cost will be $10"<<endl;
else {
cout<<"Invalid Input"<<endl;
break;
}
cout<<"Do you want to insure another animal? Enter Y for Yes or N for NO."<<endl;
cin>>continue_;
if(continue_=='n' || continue_=='N')
cout<<"Thank you for using Animal Insurance Company"<<endl;
}while(continue_ == 'y' || continue_ == 'Y');
return 0;
}

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.