Difficulty with While loop in C++ - c++

I have difficulty with my C++ assignment.
The first problem is at the end of the loop with (answer != "yes" && customers <= 5), the output is not working, because it gives both condition. The second problem is that the code is too complex and need to be simplify (any suggestion)?
The code:
#include <iostream> // Access output and input stream
#include <string> // Access string variable
using namespace std;
int main() {
int characters, food, movie, customers=0; //Declare variables
char gender; //Declare variables
string name, answer; //Declare variables
cout <<"Is there a customer? <enter yes if there is and anything else to end program>"<<endl;
cin>>answer;
while (answer == "yes")
{
customers++;
cout <<"\nWhat is your name dear? ";
cin >> name;
cout <<"Well "<<name<<", welcome to my salon!\n";
cout <<"I will ask you a few questions and your answers will determine which haircut I will give you.\nPlease enter your choice by using the character between < > next to your choice.\n\n";
cout <<"Are you <m>ale or <f>emale? ";
cin >>gender;
if (gender == 'm')
{
cout <<"Are you a Super Hero<0> or a Super Villain<1>? ";
cin >>characters;
if (characters == 1)
{cout <<name <<", You should get a mohawk.\n";}
else if (characters == 0)
{
cout <<"OK "<<name<<", do you prefer steak<0> or sushi<1>? ";
cin >>food;
if (food == 0)
cout <<name<<", You should get a flat top.\n";
else if (food == 1)
cout <<name<<", You should get a pompadour.\n";
}
cout <<"Hope you like it!!\n------------\n";
}
else if (gender == 'f')
{
cout <<"Are you a Super Hero<0> or a Super Villain<1>? ";
cin >>characters;
if (characters == 1)
{cout <<name <<", You should get a mohawk.\n";}
else if (characters == 0)
{
cout <<"OK "<<name<<", do you prefer anime<0> or sitcom<1>? ";
cin >>movie;
if (movie == 0)
cout <<name<<", You should go with bangs.\n";
else if (movie == 1)
cout <<name<<", You should go with feathered.\n";
}
cout <<"Hope you like it!!\n------------\n";
}
cout <<"Any other customers? <enter yes if there are and anything else if I am done for the day> "<<endl;
cin >>answer;
if (answer != "yes" && customers >= 5)
cout<<"\nWell that was a good day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl;
else if (answer != "yes" && customers < 5)
cout<<"\nWell that was a poor day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl;
}
cout<<"\nWell that was a poor day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl;
return 0;
}

Put the if else condition outside the while loop and remove cout<<"\nWell that was a poor day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl; outside your while loop.
while (answer == "yes")
{
...
}
if (customers >= 5)
cout<<"\nWell that was a good day! I had "
<<customers
<<" customer<s> today. Tomorrow is another day ..."
<< endl;
else
cout<<"\nWell that was a poor day! I had "
<<customers
<<" customer<s> today. Tomorrow is another day ..."
<< endl;

Related

My do while loop does not work, im not sure where I went wrong [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 1 year ago.
Improve this question
The area that I think needs work is the do while loop because I want it to loop when it only ties. However it also loops when the user wins or loses.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int ROCK = 1;
const int PAPER = 2;
const int SCISSORS = 3;
int getComputerChoice();
int getUserChoice();
void displayChoice(int);
int winner(int, int);
MAIN FUNCTION
int main()
{
int computerChoice,
userChoice;
int playAgain;
THE DO WHILE LOOP DOES WORK BUT IF I WIN OR LOSE IT STILL LOOPS. I JUST WANT IT TO LOOP IF A TIE OCCURS.
do
{
computerChoice = getComputerChoice();
userChoice = getUserChoice();
displayChoice(computerChoice);
playAgain = winner(computerChoice, userChoice);
} while (playAgain == 1);
return (0);
}
THIS GETS THE COMPUTER CHOICE
int getComputerChoice()
{
unsigned seed = time(0);
srand(seed);
return (rand() % (SCISSORS - ROCK + 1)) + ROCK;
}
THIS IS GOOD I THINK
int getUserChoice()
{
int uChoice;
cout << "Enter your choice of Rock, Paper, Scissors.\n"
<< "(1) For rock, (2) for paper, (3) for scissors: ";
cin >> uChoice;
while (uChoice < 1 || uChoice > 3)
{
cout << "Please enter a number between 1 and 3. Try again, thank you.";
uChoice = getUserChoice();
}
return uChoice;
}
THIS IS GOOD I THINK.
void displayChoice(int computerChoice)
{
cout << "Computer Choice: ";
if (computerChoice == 1)
cout << ROCK;
else if (computerChoice == 2)
cout << PAPER;
else if (computerChoice == 3)
cout << SCISSORS;
cout << endl;
}
AREA I THINK NEEDS WORK.
int winner(int computerChoice, int userChoice)
{
int playAgain = 1;
if (computerChoice == ROCK)
{
if (userChoice == SCISSORS)
{
cout << " You lose :( (The Rock smashes the Scissors) ";
}
else if (userChoice == PAPER)
{
cout << "You win! (Paper beats rock) ";
}
else if (userChoice == ROCK)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
else if (computerChoice == PAPER)
{
if (userChoice == ROCK)
{
cout << "You lose :( (Paper wraps rock)";
}
else if (userChoice == SCISSORS)
{
cout << "You win! (Scissors cuts paper)";
}
else if (userChoice == PAPER)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
else if (computerChoice == SCISSORS)
{
if (userChoice == ROCK)
{
cout << "You Win! (The rock smashes the scissors.)";
}
else if (userChoice == PAPER)
{
cout << "You lose :(. (Scissors cuts paper.)";
}
else if (userChoice == SCISSORS)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
cout << endl;
return playAgain;
}
Within winner, you attempt to update playAgain with playAgain == 0. But == is the equality operator. It does not perform assignment. The assignment operator is =, i.e. a single equal sign. As a result, playAgain is never updated, and winner() always returns 1.
To fix, use the assignment operator instead of the equality operator when updating a variable's value.

C++ While statement not working with string and "or"

I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always runs the if not the else. I feel it has something to do with it being a string, so I tested it without the or "||" and it worked. So maybe it has to do with combining strings and or statements. So did research on using these together and could not find much. Thanks for the help.
int main()
{
int year;
int day = 0;
string month = "x";
do
{
if (day == 0)
{
cout << "hello" << endl;
cout << "Please Enter your B-Day as Day, Month, Year" << endl;
cout << "day" << endl;
cin >> day;
}
else
{
cout << "Please enter a correct day" << endl;
cin >> day;
}
} while (day > 31 || day < 1);
do
{
if (month == "x")
{
cout << "Please enter the month you were born" << endl;
cin >> month;
}
else
{
cout << "Please Enter a correct Month." << endl;
cin >> month;
}
}
**while (month != "june" || month != "july");**
return 0;
}
If you do:
while (month != "june" && month != "july");
Or alternatively,
while (!(month == "june" || month == "july"));
Rather than:
while (month != "june" || month != "july");
Your program will be working fine even with multiple logical OR.
while (month != "june" || month != "july");
There is something called short-circuit evaluation in C++ which will in this case will not evaluate the right of || if the first operand returns true. Likewise for &&, it will not evaluate right operand if first is false. So be sure how you want the logic to behave and write the code.

Stuck on infinite loop

noob programmer here. Taking my first CS class in college and making first post on here so excuse me if the info i provide is not sufficient in advanced.
Still trying to figure out loops. Seem to get it but once there is loops within loops or if statements inside loops, I get thrown off and have no idea on how to proceed. For my assignment, I need the following to occur.
Would you like to process all the records in the file? (y/n) W
Please enter either y or n.
Would you like to process all the records in the file? (y/n) n
Enter number of records to process: two
XXXXXXXXXX Error-non numeric or negative value, try again
Enter number of records to process: 10
Here is my code:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
do{
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
}
else{
notDone = false;
}
}
}else if(a != 'y' or a != 'n');
cout <<"Please enter either y or n." << endl;
}while( a != 'y');
Most problems are explained in comments, here is how I would fix it:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
while (a != 'y') {
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
} else {
notDone = false;
}
}
} else if(a != 'y' or a != 'n') {
cout <<"Please enter either y or n." << endl;
cin >> a; // Need to get new input because old one is invalid.
}
};
Also I don't see how notDone is used. Also I would strongly advise of using proper indentation, spaces around keywords as while, for, if, else as it is good style.
You just put the y/n solicitation out of your loop then 'a' won't never change its value. Take a look of the change you may want:
do {
cout << "Would you like to process all the records in the file? (y/n/f) "; //f to break the loop
cin >> a;
bool notDone = true;
if (a == 'n') {
//. . .
} else if (a == 'y') {
//You may want to do something when yes
} else if (a != 'f')
cout <<"Please enter either y/n or f." << endl;
} while( a != 'f')

What is wrong with my do...while logic, and continue logic?

I'm new to stackoverflow, and also somewhat new to programming, so please don't mind my poor formatting of the code. I have two problems with my code.
My continue statement, which I'm using to continue the loop if the player types 'y' or 'Y', doesn't work. It terminates the program after only getting the guess correctly, which leads me to:
2.My continue counter goes past 0 without stopping, and I just can't see my error in the logic of the program.
I can't see the problems with my logic.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
#include <random>
using namespace std;
int getNumber(); //random number prototype
double getScore(); //gets score
int chances = 7; //chances to guess with
int main()
{
int guess = 0,
random;
char retry = 'y'; //initialize retry to 'y'
cout << "This is a random number guessing game. " << "You will be guessing between 1-100."
<< "You have 7 chances. Good luck! \n \n" << endl;
random = getNumber(); //give the function a variable
do
{
cout << random << "\n" << "\n";
chances--;
cout << "Enter your guess: ";
cin >> guess;
if (guess == random)
{
cout << "You have won the game! " << "Your score was: " << getScore();
cout << "Would you like to retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue; //player can retry the game
}
else if (chances == 0)
{
cout << "You have no chances left. Retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue;
}
}
return 0;
}
else if (guess != random)
cout << "You got it wrong. \n" << "You have: " << chances << " chances left" << endl << endl;
else
cout << "Incorrect Input. Please type a number." << endl << endl;
} while (guess != random);
return 0;
}
int getNumber()
{
unsigned seed = time(0); //seed the random number
srand(seed);
int randNum = rand() % 10 + 1; //random number in the range of 1-10
return randNum;
}
if (retry == 'y' || 'Y')
This is incorrect logic, which is why your code does not work the way you want it to. You want it to be:
if (retry == 'y' || retry == 'Y')
Fix this logic error in your other if-else statements as well.
You'll wanna take a look at this
Your continue statement is jumping to the end and checking the condition, guess != random, which evaluates to false and exits the do while. What you need to do is reset guess to a value such as 0 so that the condition does evaluate to true.

Code not working? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am learning C++. As a homework I've started to try the branching.. but I didn't quite get the hang of it... here's the code I've tried to perform (please bear patience with me if I'm making huge mistakes..)
#include <iostream>
using namespace std;
int main () {
int age;
char * yes;
char * no;
bool Rated = Rated ? yes : no;
int ticketPrice = 5;
int discountPrice = ticketPrice - (ticketPrice * 0.1);
int matineePrice = (ticketPrice * 0.5);
int hour = 8 <= hour <= 24;
cout << "Is the movie R_rated? \n";
cin >> yes or no;
cout << "How old are you?";
cin >> age;
if (age < 0 or age >100) {
cout << "Not a valid age!";
}
else if ((age <= 13) and (Rated = yes)) {
cout << "You must be accompanied by a Janitor";
}
else if (((age > 13) and ((Rated = yes) or (Rated = no)))
or ((age <=13) and (Rated = yes))) {
cout << "What time do you want the ticket for?";
cin >> hour;
if (hour < 8 or hour > 24) {
cout << "Not a valid hour!";
}
else if (hour < 18) {
if (age <= 5) {
cout << "The entrance is free";
}
else if (age >= 55) {
cout << "Matinee Ticket price is "<<
matineePrice;
}
else if (5 < age < 55) {
cout << "Matinee ticket price is " << matineePrice;
}
}
else if (hour >= 18) {
if (age <= 5) {
cout << "The entrance is free";
}
else if (5 < age <= 55) {
cout << "Ticket price is " << ticketPrice;
}
else if (age > 55) {
cout << "You're eligibile for a 10% "
"discount \n";
cout << "Ticket price is " << discountPrice;
}
}
}
}
Output: (to which I answer no, 67, and 20) and I should get the discountedPrice instead of the ticketPrice value...
Is the movie R_rated?
no
How old are you?67
What time do you want the ticket for?20
Ticket price is 5
Any suggestion, link or tutorial help would be really appreciated...
There are a lot of things wrong with your code. I suggest you get a good book on C++ and learn from that. If you're already using a book, chances are that it's not good.
Here are some things, though:
char* is not the right thing to use for strings. You should use the std::string class.
Your entire code surrounding Rated bears little resemblance to C++.
= is the assignment operator. It cannot be used to compare things for equality; that's what == is for.
To start with, get rid of yes and no, which make no sense, and read the input into a string variable:
string Rated;
cin >> Rated;
then to use that, remember to use == not = for comparison:
if (Rated == "yes") {/*whatever*/}
Alternatively, use a boolean variable:
string yes_or_no;
cin >> yes_or_no;
bool Rated = yes_or_no == "yes";
if (Rated) {/*whatever*/}
Also, this:
8 <= hour <= 24
doesn't do what you think it does. You'd need two separate comparisons:
8 <= hour and hour <= 24
although, in this case, you don't want it at all - it doesn't make sense to initialise hour with that. You're reading the value of hour and checking its range later, and don't need to initialise it here.
There are probably more problems, but that should get you started. And I hope I can still go to the cinema when I'm over 100.
The code below is fixed. I've attempted to explain exactly what the code does.
// Declare the input/output streams, including standard streams like std::cin and std::cout.
#include <iostream>
// Declare the std::string class - it's C++, we should not use C strings!
#include <string>
// Instead of using the entire std namespace, we'll only use the things that come up often.
// This saves some typing, but is safe. Otherwise, who knows what name may clash with something
// in the vast std namespace.
using std::cin;
using std::cout;
using std::endl;
int main() {
bool ok; // Whether the most recent answer to a question is valid
bool rated; // Whether the movie is R-rated
int age; // Customer's age
int hour; // Hour of the showing
const int ticketPrice = 5;
const int discountPrice = ticketPrice * (1.0 - 0.9);
const int matineePrice = ticketPrice * 0.5;
// Gather Inputs
do {
std::string answer; // Holds the answer to the yes/no question
cout << "Is the movie R-rated (y/n)? ";
cin >> answer;
if (answer.length() > 0) {
// If the answer is not empty, we can uppercase the first letter.
// This way we don't have to check for lowercase answers.
answer[0] = toupper(answer[0]);
}
// The answer is valid when it's non-empty and when it begins with either Y/y or N/n
ok = answer.length() > 0 and (answer[0] == 'Y' or answer [0] == 'N');
if (not ok) {
cout << "That's not a valid answer." << endl;
} else {
// The answer is valid, so we can set the rated variable.
rated = answer[0] == 'Y';
}
} while (not ok); // Repeat the question while the answer is invalid
do {
cout << "How old are you? ";
cin >> age;
// The answer is valid when it's between 0 and 150, inclusive.
ok = age >= 0 and age <= 150;
if (not ok) {
cout << "That's not a valid age!" << endl;
}
} while (not ok);
do {
cout << "What hour do you want the ticket for? ";
cin >> hour;
// The hour 0 is mapped to 24.
if (hour == 0) hour = 24;
// The answer is valid when it's between 8 and 24, inclusive.
ok = hour >= 8 and hour <= 24;
if (not ok) {
cout << "That's not a valid hour!";
}
} while (not ok);
// Output the Messages
if (rated and age <= 13) {
cout << "You must be accompanied by a Janitor" << endl;
}
if (age <= 5) {
cout << "The entrance is free" << endl;
}
else if (hour < 18) {
cout << "Matinee ticket price is " << matineePrice << endl;
}
else {
if (age <= 55) {
cout << "Ticket price is " << ticketPrice << endl;
}
else {
cout << "You're eligibile for a 10% discount." << endl;
cout << "Ticket price is " << discountPrice << endl;
}
}
}
To start off with:
char * yes;
char * no;
// ...
cin >> yes or no;
makes no coding sense what-so-ever.
In general, "yes" and "no" are not keywords in c++. "true" and "false" are.
Alright, some things:
1)
cin >> yes or no;
should be:
cin >> Rated;
since variable names can't have spaces in them, as you've written it the compiler reads "cin should put something in yes, but I can't figure out what to do with 'or' and 'no'."
2)
else if ((age <= 13) and (Rated = yes))
will never work. I recommend rewriting storing the result in a string (std::string) and then setting rated according to that.
std::string rated_str;
cin >>rated_str;
if(rated_str == "yes") {
rated = true;
} else {
rated = false;
}
and then in the if you use:
if(rated)
or
if(rated == true)
3) You can't reference a variable before it's fully declared:
bool Rated = Rated ? yes : no;
Lines:
bool Rated = Rated ? yes : no;
cin >> yes or no;
and all with
(Rated = yes)
(Rated = no)
have no sense.
First of all, if Rated is bool then you can assign to it only true or false (everything which is not 0 or NULL and what compiler accept would be converted to true).
Best quality code should use enum type for rated.
When you read, you should read to some variable and check its type.
Small fixes for you:
enum EnRated
{
RRated = 0,
NotRRated = 1
};
...
enum EnRated Rated;
string ans; //instead of yes, no
...
cin >> ans;
if(ans == "yes") Rated = RRated;
else Rated = NotRRated; //handle ans != yes or no
...
(Rated == RRated) // instead of (Rated = yes)
(Rated == NotRRated) // instead of (Rated = no)
For discount ticket use:
double discountPrice = 0,9*ticketPrice;
You will input hour and test them, so you can write only:
int hour;
Try this
You are doing a mistake in the following else if statements.
You are not using your else if condition checker properly.
You need not to use or keyword here... actually this is the real problem you are facing here, and you just need to replace your or with and.
For a perfect solution please read the Right approach below
Your code
else if (5 < age <= 55) {
cout << "Ticket price is " << ticketPrice;
}
Right approach
This will give you your discount price
else if (5 < age and age < 55)
{
cout << "Ticket price is " << ticketPrice;
}