My C++ program will not exit while loop below when the user enters either 'Q' or 'q' to quit the program. The first two options work fine and call their appropriate functions, but the 'Quit the program' option just starts the while loop over again indefinitely.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
char choice; //Varible to hold the user's choice.
while (choice != 'Q' || choice != 'q')
{
//Display the menu and retrieve the user's choice.
cout << "Please choose from one of the options below:\n\n";
cout << "A. Calculate the total amount of your bill [Enter A]\n";
cout << "B. Calculate your BMI [ENTER B]\n";
cout << "Q. Quit the program [Enter Q]\n\n";
cout << "Enter your choice: ";
cin >> choice;
//Either calculate the user's bill or their BMI based on their choice.
if (choice == 'A' || choice == 'a')
{
caLculateBillAmount();
}
else if (choice == 'B' || choice == 'b')
{
calculateBMI();
}
}
return 0;
}
You should simply use while (choice !='Q' && choice !='q') {...}. And yes, you should initialize choice to something different from 'Q' and 'q'. Just do something like char choice=0;.
Ask yourself what the following evaluates to:
choice != 'Q' || choice != 'q'
If choice is 'Q' then choice is not 'q' so the right-half of the test is true.
If choice is 'q' then choice is not 'Q' so the left-half of the test is true.
You need to use && in place of ||, or you could simply use toupper(choice) != 'Q'.
Related
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')
I am doing the basic console c++ "do u want to rerun program?" dance,
and failing. This is what I'm using
int main()
{
char repeat = 'y';
while (rep == 'y' || 'Y')
{
{
//primary code is here
}
cout << "\n\tRerun program? y/n";
cin >> repeat;
if (rep == 'n' || 'N')
{cout << "\n\tExiting program\n";}
}
return 0;
}
When my program finishes, it restarts and outputs "Exiting program"
no matter what I input at "Rerun program?"I understand this has
something to do with flushing or resetting the char "repeat"?
No idea how to do that and google isn't helping.
I can submit the primary program code on request, but I doubt it has
anything to do with this error.
if (rep == 'n' || 'N') will be always true,
because it actually doing if( (rep =='n') or 'N') ('N' has nonzero value which mean the if-statement is doing : if( (rep =='n') or true) ), so you always got "Exiting program" printed.
you should you if (rep == 'n' || rep =='N')
and the same, your while statement should be while (rep == 'y' || rep == 'Y')
OR
move the
cout << "\n\tExiting program\n";
out your while loop without condition to get it printed only when finish the loop
I'm stuck as to why the condition below isn't triggering when either an 'n' or a 'y' is entered at the console. When executed you can't get out the the if statement, but i know for sure that
!(cin >> again)
isn't the culprit, as that was previously the only condition in the if statement and I was able to skip/enter the if block if a character/numeral was entered, which was as expected. Here is the code:
char again;
while (1) {
cout << endl;
cout << "I see another one, care to shoot again? (y/n): ";
if (!(cin >> again) || (again != 'n') || (again != 'y')) {
// Error checking for numberals & non 'y' or 'n' characters
cout << "Please enter 'y' or 'n' only." << endl;
cin.clear();
cin.ignore(1000, '\n');
continue;
}
break;
}
I'm stumped on this so any help would be hugely appreciated!
if(...|| (again != 'n') || (again != 'y')) {
is faulty logic. What you say is
if "again" is not n or it's not y, then do the following...
now, since "again" can't be n and y at the same time, this always evaluates to true; most probably, even your compiler notices that and just jumps right into your if's content.
What you want is something like
if(!(cin>>again) || ( again != 'n' && again != 'y') {
Because that reads
if cin>>again didn't work or again is neither n nor y then,...
A bit earlier on an IRC channel, someone asked a question about his code - essentially, his program was running on an infinite loop:
#include <iostream>
using namespace std;
int main()
{
cout << "This program adds one to your input." << endl;
char choice = 'n';
int num = 0;
while (choice != 'y' || choice != 'Y')
{
cout << "Enter number: ";
cin >> num;
num++;
cout << "Your number plus 1 is: " << num << endl;
cout << endl << "Continue/Quit? Type 'Y' to quit, any other key to continue: ";
cin >> choice;
}
cout << "By choosing 'Y', you exit the loop." << endl;
return 0;
}
Paying attention to the loop header, it seems that the loop should be working perfectly fine, but whenever it comes time for me to enter Y or y in order to exit, the loop keeps running. Considering that the while loop won't evaluate the expression to the right if the one on the left is true, this makes it especially confusing. But in any case, even if I input Y or y the loop keeps running! I'd like a somewhat in-depth explanation of why this happens, I've been trying to reason it out, look back in my textbook etc. but I can't seem to understand why... I've changed the OR into an AND, but what makes OR so bad and causes it to malfunction?
Thanks all.
Condition (choice != 'y' || choice != 'Y') is always true, so loop will run indefinetely.
If choice == 'y', then you get (false || true) == true;
if choice == 'Y', then you get (true || false) == true.
You need to use while(choice != 'y' && choice != 'Y') instead, in this case you exit loop only if you get 'y' or 'Y', otherwise you get (true && true) and continue.
The OR operator between many statements returns true if at least 1 of the statements is true, no matter if the others are false or true. In your case, choice != 'y' || choice != 'Y' will be evaluated like this:
First statement is true: Execute while loop.
First statement is false: Check if the second statement is true.
Second statement is true: Execute while loop.
Second statement is false: don't execute while loop.
Specifically, when the compiler arrives at choice != 'y', if choice == 'Y', then it will still execute, because choice != 'y' is true, in fact choice is equals to Y, so it's different from y.
If, on the other hand, choice is equals to y, then it will check if the second statement is true, but we know that choice is equals to y, so choice is different from Y, and so on...
You make a mistake,you should change "||" to "&&"
How can I get my code to detect me hitting the enter key? I tried using cin.get() without any success. Also when the enter key is pressed, I'd like to change a boolean x from true to false.
Why doesn't this work?
if (cin.get() == '\n'){
x = false;
}
I'd like to end my loop (and thus and the program) when the enter key is pressed (see code below)
All code (simple rock, paper, scissors game):
#include <iostream>
#include <string>
#include <cstdlib> //random
#include <time.h> //pc time
using namespace std;
int main()
{
string rpsYou;
string rpsCom;
string winner;
bool status = true;
while (status){
cout << "Welcome to Rock, Scissors, Paper!\nYou'll have to compete against the computer."
" Please enter 'Rock', 'Paper' or 'Scissors' here: ";
cin >> rpsYou;
//Random number
srand (time(NULL));
int randomNum = rand() % 4; // -> (rand()%(max-min))+min;
//Computers guess
if (randomNum ==1){
rpsCom = "Rock";
}
else if (randomNum ==2){
rpsCom = "Paper";
}
else {
rpsCom = "Scissors";
}
//First letter to capital
rpsYou[0] = toupper(rpsYou[0]);
if (rpsYou == "Rock" || rpsYou == "Paper" || rpsYou == "Scissors"){
cout << "You: " << rpsYou << "\nComputer: " << rpsCom << "\n";
}
else {
cout << "ERROR: Please enter 'Rock', 'Paper' or 'Scissors'.";
}
if ( (rpsYou == "Rock" && rpsCom == "Rock") ||
(rpsYou == "Paper" && rpsCom == "Paper") ||
(rpsYou == "Scissors" && rpsCom == "Scissors") ){
cout << "Tie :|";
}
else if( (rpsYou =="Rock" && rpsCom =="Scissors") ||
(rpsYou =="Paper" && rpsCom =="Rock") ||
(rpsYou =="Scissors" && rpsCom =="Paper")){
cout << "Congratulations! You won! :)";
}
else{
cout << "Oh no! You lost! :(";
}
}
return 0;
}
You could do:
cout << "Hit enter to stop: ";
getline(cin, rpsYou);
if (input == "") {
status=false;
}
This is assuming there's nothing in the user input, (i.e: the user just simply presses enter)
You can't detect what key was pressed in standard C++. It's platform dependent. Here is a similar question that might help you.
Sounds like you are thinking of getting key presses "in real time", like might be useful in a game for example. But cin does not work like that. There is no way to "detect when user presses enter" in standard C++! So you can not end the program when user presses enter. What you can do is end the program when user enters empty line, or when user enters for example "quit" (or whatever, up to you), but every user input must end in them pressing enter.
Reading from cin is just like reading from a text file, except this text file gets a new line every time user presses enter. So closest thing to detecting user pressing enter is using std::getline:
std::string line
std::getline(std::cin, line);
This will get all characters from stdin until a newline (or until end of file), which usually means user pressed enter, when this is used in a console application. Note that the actual end-of-line will not be stored in the string, so if user just pressed enter without typing anything else, line will be empty string.
Looking at question after edit, you could replace cin >> rpsYou; with getline(cin, rpsYou);. You might then also want to add trimming the string you read, in case user for example typed extra spaces.