Issue with and if statement containing a string in c++ - c++

#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...
}

Related

I seem to be having trouble with basic if/else statements :/

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'

passing a bool value to another function not working properly?

Very new to C++, only been working with it for a few days. I'm trying to write a simple console calculator that requests the user input a Y or N to confirm that the result printed was actually correct.
I've called to a function that requests the user input a char for Y/N, which then returns that as a bool value as either true or false depending on what was inputted. It then returns to main with that bool, which is then passed onto another function that prints text depending upon whether true or false was passed. However whenever I run the program, it always prints both statements for true and false. I'm sure I've broken some kind of rule when using bools or there's some sort of small error but I can't seem to find it. Any help would be greatly appreciated.
bool getConfirmation()
{
std::cout << "Is this result correct? Y/N: ";
char confirm;
std::cin >> confirm;
if (confirm == 'Y', 'y') return true;
if (confirm == 'N', 'n') return false;
else return false;
}
void confirmResult(bool confirm)
{
if (confirm == true)
std::cout << "Result is correct.";
if (confirm == false)
std::cout << "Sorry, please try again.";
else
std::cout << "Sorry, please try again.";
}
int main()
{
std::cout << "Please input the first integer: ";
int x{ getInteger() };
std::cout << "Please input the desired operation: ";
char op{ getOperation() };
std::cout << "Please input the second integer: ";
int y{ getInteger() };
int result{ calculateResult(x, op, y) };
printResult(result);
bool confirm{ getConfirmation() };
confirmResult(confirm);
return 0;
}
confirm == 'Y', 'y' doesn't do what you think it does - this is an expression involving the built-in comma operator, which always evaluates to 'y'. The correct code is:
confirm == 'Y' || confirm == 'y'
You will always see both
std::cout << "Result is correct.";
std::cout << "Sorry, please try again.";
being executed because your boolean logic is incorrect.
if (confirm == true)
A
if (confirm == false)
B
else
C
If confirm == true, then both A and C will be executed, as the second if statement is not introduced by an else. Your logic should just be:
if (confirm == true)
std::cout << "Result is correct.";
else
std::cout << "Sorry, please try again.";

My program keeps looping and never get's to "return 0;". Is it the compiler that's bad or the code? [duplicate]

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.

Why is this only returning "yes"

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)

C++ 'else' in loops

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.