Why does my function get read, but become an infinite loop? [duplicate] - c++

This question already has answers here:
If statement runs through whether conditions are met or not
(4 answers)
Closed 2 years ago.
Hello I'm having a problem where when I call my function after the user enters "Y" to start the game, the cout gets read but it becomes an infinite loop. It works just fine when you enter "N" or something thats not supposed to be entered. I am using a header file called functions to well, put all the functions if that has anything to do with it. I am still in the very early learning stages of programming, and run into so many speed bumps and just not quite sure where to turn. Any help is appreciated. (P.S. I have not yet started on the gameStart() function just because of this problem. That's not whats it's going to be in the end.)
#ifndef FUNCTIONS_H;
#define FUNCTIONS_H
#include <iostream>
using namespace std;
void startScreen()
{
void gameStart();
char answer;
cout << "Welcome to __________\n\n";
cout << "This is my fisrt ever actual program I made out of my own free will lol.\n";
cout << "It is a Text-Based Adventure game. In this game you will make a character,\n";
cout << "and explore the land of Spelet, battling enemies, leveling up, getting loot,\n";
cout << "and learning skills! You do not need to capitalize anything but your character\n";
cout << "name. If a question has (something like this), those are the choices for that \n";
cout << "interaction! Thank you for trying out my terrible little game! :)\n";
cout << "I really hope y'all enjoy it!\n\n";
cout << "Would you like to play?\n";
cin >> answer;
do
{
if (answer == 'Y' || answer == 'y')
{
gameStart();
}
else if (answer == 'N' || answer == 'n')
{
cout << "Program will now close...\n";
system("pause");
exit(0);
}
else
{
cout << "Enter a Y for yes or an N for no.\n";
cout << "Would you like to play?\n";
cin >> answer;
}
}
while (answer != 'N', 'n' || 'Y', 'y');
}
void gameStart()
{
cout << "\n\"BOOM-BOOM-BOOM...\"\n\n" << endl;
}
#endif

maybe you need:
while (answer != 'N' && answer != 'n' && answer != 'Y' && answer != 'y')

The comma operator doesn't do what you think it does. It "discards the result," as my link says.
You want the && operator (AND operator) instead:
while (answer != 'N' && answer != 'n' && answer != 'Y' && answer != 'y');

Related

While Loop when to use OR or AND? [duplicate]

This question already has answers here:
While loop with multiple conditions in C++
(4 answers)
Closed 2 years ago.
I need help with this simple question.
I'm starting to learn more about while loops and I'm not sure what I'm doing wrong.
Here's a snippet of the code that I'm working on, so when I'm using or in while loop the loop executes indefinitely. But when I use AND the loop stops can somebody please explain? Shouldn't OR be used instead as per definition?
void displayMenu() {
char option;
while (option != 'Q' or 'q') { //And or OR?
cout << "P - Print numbers" << endl;
cout << "A - Add a number" << endl;
cout << "M - Display mean of the numbers" << endl;
cout << "S - Display the smallest number" << endl;
cout << "L - Display the largest number" << endl;
cout << "Q- Quit" << endl;
cout << "Choose Your Option-" << endl;
cin >> option;
if (option == 'P' or 'p')
Print();
}
}
You have phrased your condition (option != 'Q' or 'q') like you speak it.
"option not upperQ or lowerQ".
That is understood by the compiler as "option is not upperQ; or q", where "q" is a non zero thing. Nonzeros are interpreted as "true". So the whole thing always evaluates to "true", always, even for option having a values like 'Y' or '2'.
You have to rephrase much less coloqually as
"option is not 'Q' and it is not 'q' "
and you have to use the appropriate operators. Using additional () to make sure that what you mean is understood does not hurt.
That is done as
( (option != 'Q') && (option != 'q') )
Using or, or in this case and instead of the logical && is possible in certain situations, and the additional () are not required either. The main issue is however with your choice of "or" instead of "and" and using the () is a safe way as long as you are not very familiar with the operators and their order of evaluation in expressions like this one.
Why exactly you need to use && ("and") instead of or or || is a question of what happens with the two interesting letters. Lets take 'Q' it obviously is one of the two you are looking for. But it is not 'q'. So the second part of the condition with is true. With || that is sufficient and the whole thing is evaluated to "true" and the loop continues - obviously not what you want. The same is for 'q', it is not 'Q' and there for || continues.
What you actually want is "neither" and that is the same as "not this and not that". Hence you need "not and not", !a && !b or more bluntly explicit (option != 'Q') && (option != 'q').
That can be reprhased with implicit knowledge of operator precedence (look it up and try to memorize) to option != 'Q' && option != 'q'.

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

C++ if/else if statement not working correctly [duplicate]

This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 7 years ago.
I am trying to code a little game-like adventure program, and I need if else statements in it for it to work correctly. However, whenever I run this if else statement, it does not output what I want.
#include <iostream>
using namespace std;
int main()
{
while(true)
{
cout << endl << "What will you do?: ";
string input;
cin >> input;
if (input == "Nothing" || input == "nothing")
{
cout << "Why would you do nothing?" << endl;
}
else if (input == "Look North" || input == "Look north" || input == "look North" || input == "look north")
{
cout << "You look north. There is nothing north." << endl;
}
}
}
What I expect it to output would be this:
What will you do?: nothing
Why would you do nothing?
What will you do?: look north
You look north. There is nothing north.
What will you do?:
But instead of getting that when I put those as an input, I get this:
What will you do?: nothing
Why would you do nothing?
What will you do?: look north
What will you do?:
What will you do?:
I would like some help on resolving this issue, as I cannot find an answer to why this would be happening.
cin >> input;
does not read whitespaces. You need to use std::getline.
getline(cin, input);
Because when you input "Look north"
using
cin>>input;
only "Look" is saved into the input variable ..
The problem is withcin statement as it does not handle white spaces, try what is posted here. Also, you will find helpfull the tolower() function, to normalize your inputs.

My else if statement using a string is not working [duplicate]

This question already has answers here:
if statement not working right?
(5 answers)
Closed 7 years ago.
after a good amount of time trying to get my else if statement to work, it just doesn't. This program keeps returning the first one, no matter what I input. Please help.
#include <iostream>
#include <string>
using namespace std;
string arehap;
int main()
{
cout << "Are you happy?" << endl;
cin >> arehap;
if (arehap == "Yes" || "Y")
{
cout << "Good." << endl;
}
else if (arehap == "No" || "N")
{
cout << "Bad." << endl;
}
return 0;
}
You should use this:
if (arehap == "Yes" || arehap == "Y")
{
cout << "Good." << endl;
}
else if (arehap == "No" || arehap == "N")
{
cout << "Bad." << endl;
}
When you're using the || operator, you have to compare two boolean values. If arehap is equal to "Y", the following statement will be True: arehap == "Y". In that case your computer will "understand" this as if (True || False) { /* do smth */} and this will evaluate to True and the code you want to execute will be run.
Your problem lies in this line:
if (arehap == "Yes" || "Y")
C++ understands this as
if ((arehap == "Yes") || ("Y"))
and while the first check (arehap == "Yes") might be false, the second check -- which is just "Yes" is always true.
This happens, because the "Yes" gets understood as a char const* -- and this pointer must obviously not be NULL, but point to the character 'Y'!