I am working on a c++ problem from my workbook and I have had a hard time with the behavior of the logical operators in this problem (and many others I have faced.)
Here is the code:
#include <iostream>
using namespace std;
int main()
{
string input1, input2;
cout << "Enter two primary colors to mix. I will tell you which secondary color they make." << endl;
cin >> input1;
cin >> input2;
if ((input1 != "red" && input1 != "blue" && input1 != "yellow")&&(input2 != "red" && input2 != "blue" && input2 != "yellow"))
{
cout << "Error...";
}
else
{
if (input1 == "red" && input2 == "blue")
{
cout << "the color these make is purple." << endl;
}
else if (input1 == "red" && input2 == "yellow")
{
cout << "the color these make is orange." << endl;
}
else if (input1 == "blue" && input2 == "yellow")
{
cout << "the color these make is green." << endl;
}
}
system("pause");
return 0;
}
The code works as it should the way it is written. Well, almost. I need the user input to meet certain conditions. If the user puts any color in other than red, blue, or yellow, I need the program to display an error message. It will not do so the way it is written. But with the original way it was written, it would only give me an error message, even if I would put in the requisite color. For example:
if ((input1 != "red" || input1 != "blue" || input1 != "yellow")&&(input2 != "red" ||
input2 != "blue" || input2 != "yellow"))
I tried to reason this out in pseudocode to see if it made sense, and it seems like it does. Here is my reasoning: If the input1 is not equal to red, blue, or yellow, and input2 is not equal to red, blue or yellow, return an error code.
I can't seem to figure out what I am doing wrong. Can someone walk me through this?