This question already has answers here:
How to compare multiple strings inside an if statement?
(6 answers)
Closed 4 years ago.
I have this code running by chance and when i put anything as the answer it is showing me correct. I know we have to put ans before YES and yay, but this code was compiled too, as i mentioned if i put any word as the input the output is correct:
string ans;
cin >> ans;
if(ans == "yes" || "YES" || "yay") {
cout << "Correct";
}else {
cout << "Incorrect";
}
Ok here's the precedence (L->R) and associativity of logic wise operators:
(((ans == "yes") || "YES") || "yay")
Since C/C++ has no chaining unlike Python.
1st: ans == "yes" -> str to str comparison
2nd: bool result of 1st || "YES" -> bool and str comparison = always true for "YES" is not null
3rd: true || "YES" = always true
Thus, the condition will always be true for "YES" and "yay" are not null.
You have the precedence wrong.
if (var == A || B || C) means "if (var is equal to A) OR (B is not zero) OR (C is not zero)"
You want to do if (var == A || var == B || var == C). That means "if (var is equal to A) OR (var is equal to B) or (var is equal to C)"
You should compare ans with each value. Every comparison with value is not "0" or "fail" value is assumed as "true". So if you input the if a condition like if("yes") it always returns a true.
int main()
{
std::string ans;
std::cin >> ans;
if("yes" == ans || "YES" == ans || "yay" == ans)
{
std::cout << "Correct\n";
}
else
{
std::cout << "Incorrect";
}
}
Related
I'm trying to code a blackjack game and everything is going smoothly so far but for this bit. No matter what I input into hitStand it always goes to the first if statement and "hits". I would like for if "h" is inputted it "Hits" and if "s" is inputted it "Stands" and, if there is an invalid input, it will tell the user to try again.
I'm still fairly new to C++, so some help would be appreciated.
while (repeat == 0)
{
char hitStand;
cout << "Would you like to HIT or STAND [H/S]";
cin >> hitStand;
if (hitStand = "H" || "h")
{
PcardNew = rand() % 13 + 1;
cout << endl;
cout << "Your new card is: " << PcardNew << endl;
if (PcardNew > 10)
{
PcardNew = 10;
}
playerTotal = playerTotal + PcardNew;
cout << "Your new total is: " << playerTotal << endl;
}
else if (hitStand = "S" || "s")
{
break;
}
else
{
cout << "Please enter a valid imput [H/S]" << endl;
}
}
There are (at least) three errors in the single if (hitStand = "H" || "h") line!
First, the = operator is an assignment, not a comparison; to test for the equality of two operands, you need the == operator.
Second, the "H" and "h" constants are string literals - that is, multi-character, null-terminated strings of characters. Use single quotes for single characters (thus, 'H' and 'h').
Third, you can't compare one object with two others like that with a logical or (||) operator. You need to make two separate comparisons and then or the results of each:
So, use this:
if (hitStand == 'H' || hitStand == 'h')
{
//...
And similarly for your second test:
else if (hitStand == 'S' || hitStand == 's')
{
//...
That is because your condition in if statement is always true. Since "h" is in or (||).
Instead use:
if (hitStand == 'H' || hitStand == 'h')
and
else if (hitStand == 'S' || hitStand =='s')
This question already has answers here:
if statement not working right?
(5 answers)
Can you use 2 or more OR conditions in an if statement? [duplicate]
(9 answers)
Closed 4 years ago.
I am trying to create a simple c++ program which prints out if char is Y or y, N or n or neither.
After debugging I have found out that the if(chr == 'Y' || 'y') statement is true even though char variable is 'N'. Can anybody tell me why this if statement is true and not false?
#include "pch.h"
#include <iostream>
using namespace std;
void main()
{
char chr = 'N';
if (chr == 'Y' || 'y')
{
cout << "chr is y" << endl;
}
else if (chr == 'N' || 'n')
{
cout << "chr is n" << endl;
}
else
{
cout << "chr is something else" << endl;
}
}
This is not doing what you thing:
if (chr == 'Y' || 'y')
This is basically:
if (chr == 'Y' || true)
So in the end:
if (true)
You have to say what you compare:
if (chr == 'Y' || chr == 'y')
The operator == only takes one character, not a set of possible characters.
Instead of this
if (chr == 'Y' || 'y')
You need
if ((chr == 'Y') || (chr == 'Y'))
Likewise for the 'N' and 'n'.
It is also possible do it with one comparison:
if (toupper((unsigned char)chr) == 'Y')
This way, maintainability is slighly improved as only one value has to be changed should the letter change (for a different localization, per example).
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'!
I'm just stuck on some logic statements.
specifically the ones that are in the function char GetInteger() so how would I only allow 3 values to cause the loop to exit.
char GetInteger( /* out */ char& usrinput)
{
do
{
cin >> usrinput;
cin.ignore(200,'\n');
if (usrinput != 0 || usrinput != 1 || usrinput != 2)
{
cout << "Invalid Input." << userinput << " Try Again\n";
}
} while(usrinput != 0 || usrinput != 1 || usrinput != 2);
return userInput;
}
Two issues with this code:
First userinput has a type of char. So when you read from a stream you read a single character (after dropping white space). So when a user types 1<enter> you get the character '1' in the variable userinput. Note the character '1' is not the same as the number 1.
Thus your test should be:
userinput != '1';
Secondly your boolean logic is wrong. When first learning it is sometimes easier to state the problem as a list of values that you would like to be acceptable (not the unacceptable ones).
You want the conditions to be false if the userInput has one of your accepted values (any good value will fail the test and thus not invoke the bad code). The first step to this is to get a true if any of your values are valid.
// If any value is good then true.
userinput == '1' || userinput == '2' || userinput == '3'
To invert this just add a not to the expression.
if (! (userinput == '1' || userinput == '2' || userinput == '3') )
Note: in boolean logic
!(A || B) => (!A && !B)
So you could re-write the above as:
if (userinput != '1' && userinput != '2' && userinput != '3')
I think this was your main mistake you converted the == into != but did not convert the || into &&.
I would also suggest that you could simplify this (as you may get more valid result) byconverting this into a range based test.
if (userinput < '1' || userinput > '3')
{
// Test Failed.
}
Additionally. Since you have the test in two places. You should yank it outinto its own function. Then you can call the function to do the test.
bool isUserInputValid(char userInput)
{
return userInput >= '1' && userInput <= '3';
}
Now we can re-write your original function as:
char GetInteger( /* out */ char& usrinput)
{
do
{
cin >> usrinput;
cin.ignore(200,'\n');
if (!isUserInputValid(userinput))
{
cout << "Invalid Input." << userinput << " Try Again\n";
}
} while(!isUserInputValid(userinput));
return userInput;
}
First of all, you should use int instead of string as you are reading integer.
You can use while(1) instead of putting condition in while. Inside while loop, if your selection is 0 or 1 or 2, you can simply break the loop.
I am making a program that will evaluate the value of something. I have a variable that holds the total value to be added, rcoverE. When I test "y" for the second question, it works, but when I put in "n", it adds 5 anyway. Why is this happening?
#include <iostream>
using namespace std;
int main(){
int year, yearE, rcoverE;
string rcover, func;
cout << "Enter the decade your thing was produced (eg. 20):";
cin >> year;
cout << "Does you typewriter have original thingy? (y,n):";
cin >> rcover;
rcoverE = 0;
if(rcover == "y" || "Y"){
rcoverE = rcoverE + 5;
}else{
rcoverE = rcoverE + 0;
}
cout << rcoverE;
yearE = 100 - year / 2;
}
if(rcover == "y" || "Y"){
This condition is wrong it should be:
if(rcover == "y" || rcover == "Y"){
This: if(rcover == "y" || "Y"){ is logically equivalent to if(rcover == "y" || "Y" != 0) and "Y" != 0 is always true.
if(rcover == "y" || "Y")
Does not evaluate the way you think it does. This actually evaluates as if ("rcover == 'y') or if('Y')", not "rcover == ('y' || 'Y')." In some languages the compiler would not let you do this, but in C++, simply putting in the statement "Y" returns true. You need to change the statement to:
if(rcover == "y" || rcover == "Y")