int OnLoad() {
cout << "Hi whats your name? ";
cin >> name;
system("cls");
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl;
cin >> userInput;
if (userInput == "yes" || "Yes") {
cout << "Yes" << endl;
}
else if (userInput == "no" || "No") {
cout << "No" << endl;
}
else {
cout << "I don't understand." << endl;
}
return 0;
}
int main() {
OnLoad();
system("pause");
return 0;
}
This code only returns Yes back, after the console window pops up and ask are you here to take over the city from zombies even after i type no it returns yes!
if (userInput == "yes" || "Yes")
actually means
if ((userInput == "yes") || ("Yes"))
It's logical OR between two expressions: userInput == "yes" and "Yes". The first one is correct and evaluates to bool directly. The second one is just a char* that will be converted to bool implicitly. Since it's a compile time string it cannot be nullptr, which means it will always evaluate to true. And that, in turn, means the whole condition is always true (that's how logical OR works).
The correct code is
if (userInput == "yes" || userInput == "Yes")
P. S. This is why I always recommend compiling with the highest warning level possible (/W4 for MSVC, -Wall -pedantic-errors for GCC and clang). Most compilers will generate a warning in this case.
that's not how the || operator works, if you just put "Yes" as a condition it will always evaluate to true
if (userInput == "yes" || userInput == "Yes") {
cout << "Yes" << endl;
}
the reason why is because of precedence
userInput == "yes"
and
userInput == "Yes"
get evaluated before || ( logical OR)
Related
THE IDEA (C++):
The idea is simple, if you're under 21 and in full time education, you're eligible (no idea for what, it's just homework). If you're not eligible, you have to tell the user why.
int main()
{
string education;
int age;
cout << "Are you in full time education? (y/n): ";
cin >> education;
cout << "\nEnter your age: ";
cin >> age;
system("cls");
if (((education == "yes" || education == "y")) && (age <= 21))
{
cout << "You are eligible.";
}
else if (((education == "yes" || "y")) && (age > 21))
{
cout << "You are not eligible because you are over 21.";
}
else if (((education == "no" || "n")) && (age <= 21))
{
cout << "You are not eligible because you are not in full time education.";
}
else if (((education == "no" || "n")) && (age > 21))
{
cout << "You are not eligible because you are not in full time education and you are over 21.";
}
else
{
cout << "There is a problem with your input.";
}
}
THE PROBLEM:
Now, if I input that I'm NOT in fulltime education AND over 21, the output is "You are not eligible because you are over 21.", which is technically true, but it should be giving me "You are not eligible because you are not in full time education and you are over 21." instead!
Things to note:
My #include statements are cut out of the screenshot, but don't worry about them, I know they're fine.
All the "else if" statements were originally just "if", but I made them this way to try and fix the issue.. to no avail clearly.
You can't use the or operator like this
a == 'first' || 'second' // education == 'yes' || 'y'
in order to say "if a is equal to first or second", you have to repeat the a== also on the right hand side:
a == 'first' || a == 'second' // education == 'yes' || education == 'y'
#include <iostream>
using namespace std;
int main(){
cout << endl;
cout << "Welcome to the wonderful world of a spy" << endl;
cout << "Today we are to decode some information that has been provided." <<endl;
string response;
cout << "Are you ready?" << endl;
cin >> response;
if (response == "yes", "y", "Yes", "Y"){
cout << "Alright, let's go!!!" << endl;
}
else {
cout << "Well, too bad. We are going to do it anyways." << endl;
}
}
Exact Code Here is my code thus far. I can't get it to not say "Alright, let's go!!! What am I doing wrong?
The line if (response == "yes", "y", "Yes", "Y") doesn't do what you think it does. The comma operator evaluates each of its operands, discards the result on the left and takes the result on the right as the result of the expression. So what you wrote is equivalent to if ("Y"). You need to use the logical OR operator to combine your different cases. Like this if (response == "yes" || response == "y" || response == "Yes" || response == "Y").
your if statement conditions are wrong.
if(response == "yes" || response == "y" || response == "Yes" || response == "Y")
{
//then do whatever...
}else{
//do it anyway...
}
This question already has answers here:
How to compare multiple strings inside an if statement?
(6 answers)
Closed 5 years ago.
My program keeps looping and never get's to "return 0;". Is it the compiler that's bad or the code?
#include<iostream>
using namespace std;
int main() {
string nameInput = "";
string Input = "Yes";
cout << "Welcome to the purple casino!" << endl << "What's your name?" << endl;
while(Input =="Yes" || "yes"){
getline(cin, nameInput);
cout << nameInput << ", what a nice name!" << endl << "Do you want to change it?" << endl;
getline(cin, Input);
if(Input =="Yes" || "yes"){
cout << "To what?" << endl;
}
}
cout << "Let's begin!";
return 0;
}
The expression Input == "Yes" || "yes" is evaluated, due to operator precedence, as
(Input == "Yes") || "yes"
which is always true. This is because the const char[4] literal "yes" decays to a const char* type, with a non-zero pointer value.
You need Input == "Yes" || Input == "yes"
My program keeps looping and never get's to “return 0;”. Is it the compiler that's bad or the code?
The code, as (almost) always.
Input =="Yes" || "yes" will always evaluate to true, no matter what Input's value really is, since it boils down to saying:
true if: Input equal to "Yes" OR "yes".
false if otherwise.
A string literal evaluates to true, thus the second operand of the logical or will be true, causing the whole logical expression to evaluates to true, always!
As a result your while loop's condition is always true, resulting in an infinite loop!
So change this:
while(Input =="Yes" || "yes")
to this:
while(Input =="Yes" || Input == "yes")
PS: Change the condition of the if statement similarly, since it's the same exact condition.
Your while statement's condition is wrong:
while (Input == "Yes" || "yes")
as "yes" operand always evaluates to true causing the entire condition to be true. Try this instead:
while (Input == "Yes" || Input == "yes")
There is a silly mistake in your code. Please see the below edited code -
#include<iostream>
using namespace std;
int main(){
string nameInput = "";
string Input = "Yes";
cout << "Welcome to the purple casino!" << endl << "What's your name?" <<
endl;
while(Input =="Yes" || Input == "yes"){ // Error was here
getline(cin, nameInput);
cout << nameInput << ", what a nice name!" << endl << "Do you want to
change it?" << endl;
getline(cin, Input);
if(Input =="Yes" || "yes"){
cout << "To what?" << endl;
}
}
<< "Let's begin!";
return 0;
}
Try modifying while(Input =="Yes" || "yes"){ to while(Input =="Yes" || Input == "yes"){
I think the problem will be solved.
Hi before return try :
cout << "Let's begin!";
And change in While and if your condition to:
(Input =="Yes" || Input=="yes")
In a more general way, if you have a loop from which your program never returns, it means that the condition you passed always evaluates to true.
In your case indeed, an as others already answers, the condition
while (Input == "Yes" || "yes")
always evaluate to true because of the second part.
What you really want is to check if Input is "Yes" OR Input is "yes", which in C++ should be written :
while (Input == "Yes" || Input == "yes").
Hope, this more general answer will help.
In C++, I have run into a problem when I am doing loops. I just know there is an obvious solution I am just overlooking in my work. Here is an example for reference:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string loop();
int main()
{
string answer;
do
{
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO")
cout << "As you wish";
else if (answer == "yes" || answer == "Yes" || answer == "YES")
cout << "";
else
{
cout << "You didn't answer yes or no\n";
loop();
}
}while (answer == "yes" || answer == "Yes" || answer == "YES");
return 0;
}
string loop()
{
string answer;
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO")
cout << "As you wish";
else if (answer == "yes" || answer == "Yes" || answer == "YES")
cout << "";
else
{
cout << "You didn't answer yes or no\n";
loop();
}
return answer;
}
When I am doing an If-else in a loop, I run into a problem when it comes to the else section. I cant seem to figure out how to display something that tells the user there is an error, and then re-run the same sequence. For example, in the program I included, when the user enters something other than yes or no, I am not sure how to show an error statement and then loop it back to the top so it asks the question again.
You should use a while loop.
string answer;
while ( (answer != "yes") && (answer != "no") ) {
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO") {
cout << "As you wish";
break;
}
if (answer == "yes" || answer == "Yes" || answer == "YES") {
cout << "";
break;
}
}
The problem isn't the loop; the problem is you've got your logic all tangled up. The solution isn't a way to fix the loop, the solution is a way to straighten up your logic.
A simple trick which is a lot more useful than it appears is to completely separate the loop from the thing you do in the loop:
// This function does something, then returns a boolean value
// to indicate whether or not you should continue looping.
bool do_something();
int main()
{
bool continue_looping = true;
while (continue_looping) {
continue_looping = do_something();
}
}
Now, you implement do_something() in a way that doesn't have to worry about actually doing the looping; it's only responsibility in that regard is to return a value that indicates whether looping should continue.
All you need is a single do-while loop...
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string ans{""};
transform(ans.begin(), ans.end(), ans.begin(), ::tolower); // convert string to lower case
do {
cout << "Do you wish to be asked this question again? ";
cin >> ans;
if (ans == "no") {
cout << "As you wish.";
} else
if (ans == "yes") {
cout << "";
}
else {
cout << "You didn't answer yes or no." << endl;
}
} while (ans != "yes" && ans != "no");
return 0;
}
Note, the transform algorithm converts the string into lower case to avoid variations in the spelling of yes and no.
I made a little game where the program jumbles up a word and asks for player input. However, one of the If statements are giving me an error and stopping me from compiling the program.
string isready;
cin >> isready;
if (isready == 'y' || 'Y')
Above I set up a string to be called isready, than asked the user for input. As seen above,
I wanted the if statement to activate if either y or capital y was typed in and received.
However, it just gives me the error:
invalid operands to binary expression ('string'
(aka 'basic_string, allocator >') and 'int')
Perhaps I'm missing a #include file?
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] = //5x2 array
{
{"wall", "Do you feel you're banging your head against something?"},
{"glasses", "These might help you see the answer."},
{"labored", "Going slowly, is it"},
{"persistent", "Keep at it."},
{"jumble", "It's what the game is all about."}
};
srand(static_cast<unsigned int>(time(0)));
int choice = rand() % NUM_WORDS;
//Choice value in array, than area in array where word and hint are
string theWord = WORDS[choice][WORD]; //word to guess
string theHint = WORDS[choice][HINT]; //hint for word
string jumble = theWord; //jumbled version of word
int length = jumble.size();
//Index1 and index2 are random locations in the string theWord
//last two lines swaps areas, ending the for function with a different
//jumble variable every time.
for (int i = 0; i < length; ++i)
{
int index1 = rand() % length;
int index2 = rand() % length;
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "\t\tWelcome to Word Jumble!\n\n";
cout << "Unscramble the letters to make a word.\n";
cout << "\n\n\nReady? (y/n)";
//I'm asking here if the player is ready
string isready;
cin >> isready;
if (isready == 'y' || 'Y')
{
cout << "Ok this is how the scoring works\n";
cout << "The length of the word you will guess is times by 5000.\n";
cout << "If you ask for a hint, your score will go down by half.\n";
cout << "If you get the wrong answer, your score will go down by 1000.";
cout << "\nOk, lets start!\n\n\n";
int counter = 3;
for(int i = 0; i < 3; ++i)
{
cout << counter << "..." << endl;
counter--;
}
sleep(1);
}
else
{
cout << "check";
}
cout << "Enter 'quit' to quit the game.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "The jumble is: " << jumble;
//Score system
unsigned long int score;
int amount_of_guesses, amount_of_wrong = 0;
string guess;
cout << "\n\nYour guess: ";
cin >> guess;
while ((guess != theWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
amount_of_guesses++;
}
else
{
cout << "Sorry, that's not it.";
amount_of_wrong++;
}
cout << "\n\nYour guess: ";
cin >> guess;
}
score = theWord.length() * 1000 -(amount_of_wrong * 1000)
/ 2 * amount_of_guesses;
if (guess == theWord)
{
cout << "\nThat's it! You guessed it!\n";
}
cout << "Your score is: " << score;
cout << "\nThanks for playing.\n";
return 0;
}
here
(isready == 'y' || 'Y')
you are trying to use operator== on std::string and char, because 'y' is char. Apart from this conditions should be in parenthesis because || has lower precedence than ==
Correct version is:
( (isready == "y") || ( isready == "Y")) // use bool operator==
(const string& lhs,
const string& rhs);
Operator || takes logical expressions on both sides:
if (isready == "y" || isready == "Y")
Note the double quotes above, because isready is a std::string. You could also change isready to char, and use character constants (i.e. 'y' and 'Y' in single quotes).
Your current expression is syntactically valid, but it will be evaluated as unconditional true, because it is interpreted as follows:
if (isready == 'y' || 'Y' != 0)
// ^^^^^^^^
// != 0 part is implicit;
// `Y` != 0 is always true, so the entire OR is also always true
Change this statement
if (isready == 'y' || 'Y')
to
if ( isready == "y" || isready == "Y")
Take into account that there are double quotes.
The problem is that there is no such operator == that can compare an object of type std::string with an object of type char. There is no such a constructor in class std::string that could convert implicitly an object of type char to an object of type std::string. However class std::string has a constructor that can convert a string literal to an object of type std:string. So the right operand that is "y" or "y" is implicitly converted to a temporary object of type std::string. As the result in the condition above two objects of type std::string are compared.
Also the condition you wrote initially is invalid even if you would use string literals instead of character literals. If for example isready == "y" was equal to false then you will get
false || "y"
In this expression string literal "y" is converted to a pointer to its first character. As this pointer is not equal to NULL then the whole expression will be true independing of the value in isready
(isready == 'y' || 'Y')
You should check for each character seperately.
((isready == "y" || (isready == "Y"))
if (isready == 'y' || 'Y')
should be
if (isready == "y" || isready == "Y")