Conditional if statement bug - c++

For an assignment in my C++ programming class, we're supposed to create a program that will ask for order information for a product to be shipped, such as price, if it's fragile, the designated country, etc. Everything else except for one little if statement doesnt work correctly, and it's the one that prints out an error message if when typing in the country, it's not one of the three listed, no matter what I type, it always spits out the error!
if(shippingDestination!="AUS" || shippingDestination != "CAN" || shippingDestination != "USA")
{
cout<<"\nWrong destination ! Exiting........."<<endl;
system("pause");
exit(0);
}
(And yes, prior to this statement, the input by the user is forced into uppercase, and I have tested this without the statement above, everything works as intended)
I've tried several different variations to this conditional statement to try and get a favorable result, but no matter what I do, it always, always spits out the error.

There is a problem with your logical operators.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string shippingDestination="";
cout<< " Enter Destination ";
cin>>shippingDestination;
if(shippingDestination!="AUS" && shippingDestination!="CAN" && shippingDestination!="USA" ){
cout<< "Wrong Destination";
}else{
cout<< "Correct Destination";
}
}

Don't use "||"! What you want is: &&.
if (shippingDestination != "USA" && shippingDestination != "CAN" && shippingDestination != "AUS") {
cerr << "Wrong desitnation. << endl;
return 1; // It's convention to return 1 when there is an error.
}

if you use the or operator || in the if statement then if any of those conditions are true then whatever is inside the if condition is executed. What you need is the and operator && for this operator all the conditions have to be true. Also I found this answer pretty interesting
How an 'if (A && B)' statement is evaluated?

Related

C++ array greater than 0 print code

I am having issues with this block of code:
else if (mineOrRefine == "refine" || mineOrRefine == "Refine")
if (StoneInventory[0] == 0)
cout << "You currently have no stone!" << endl;
int a = StoneInventory[0];
else if (a == >1)
You're not saying what the problem is, but I can all but guarantee it has to do with a lack of braces. Put your if and else blocks into braces, even when it's just one line, to reduce confusion. I'm not going to get into a debate about whether to put braces around a single expression following if/else in general, only that, in your case, the lack of braces is confusing you, so put them in.
instead of ( a== >1), use (a>=1) or (a>0)
also, any 'if' statement with more than one line of code should use curly braces. ie: if (x) { /* code */ }.
You're lost in the ifs, and you really need to add curly braces to see what's going on. The code amounts to this:
if (something_you_havent_shown)
{
// something else you haven't shown
}
else if (mineOrRefine == "refine" || mineOrRefine == "Refine)
{
if (StoneInventory[0] == 0)
{
std::cout << "You currently have no stone!" << std::endl;
}
}
int a = StoneInventory[0];
else if (something_you_say_youve_changed_since_asking_the_question)
The else in that last line doesn't go with any preceding if -- they've all finished, because each one applies only to the next line.

Why my or operator doesn't work?

Why can't I get the right string. What do I have wrong in the expression? I can't figure it out. I've stocked for hours.
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;
int main (){
string var = "y";
string constant ="y";
if ((var != constant )||( var != "n")){
cout << "error";
}
else {
cout << "right" // this is what it should print
}
}
I understand that or operator uses || as symbol. So why can't my program perform its task
Your program's results are correct.
Since var is set to "y", then the expression
var != "n"
is obviously true.
As such, the full expression
if ( .... || var != "n")
evaluates to true. By definition "anything OR true" is always true.
No matter how much you want your else statement to execute, it will not. Because it should not be.
There is nothing wrong with your program(aside from the syntax error at line 14). Your testing if var and constant are not equal, or var does not equal 'n'. The or statement works fine, because you're basically saying: if (condition or true), which will always be true because if he or operator finds only one condition true it will return true.
I believe what you want is the and, &&, operator. It only returns true if both of its conditions are true.
That being said above, even with the && operator your still going to have to change your code. Your error\bug makes no sense. You told your program:
#pseudo code
if(false and false)
print error
else
print ...
your program is simply obeying the rules you set. The if statement above your else statement will never be reached because the if statement will always evaluate to true.

Why I cannot assign values to a variable with if and if else statements?

#include <iostream>
using namespace std;
void main()
{
int leftover;
int gold = 3900;//satisfies the if else statement
if( gold>=4100){//successfully build item
leftover = gold-4100;
}
else if(4100>gold>=3500){
leftover = gold-3500;
}
cout << leftover << endl;
system("pause");
}
This code doesn't work, it will show that leftover is used without being initialized. But when I changed the value of gold(etc 4200) to satisfy the if statement, it will work, displaying the remainder after gold has been deducted from 4100. I am just learning c++ in school so I am not familiar with if and if else statements yet so many thanks for telling me what went wrong!
4100>gold>=3500 doesn't do what you think. It's evaluated as (4100>gold) >= 3500, which depending on the value of gold can be 0 >= 3500 or 1>3500. Look up operator precedence.
You probably want
(4100>gold) && (gold>=3500)
If you don't initialize the value and the if statements fail, then you cout null
You have two suggestions here:
FIRST:
int leftover = -1; //Initialize the value
SECOND:
else { leftover = 0; } //Default the value if the if case fails
Yea I made a VERY careless mistake, the only problem is 4100>gold>3500 will never get evaluated.
Thanks to all who answered and pointed out to use AND gate instead of shared operands!

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}
If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}
if (m==n){
cout<<"Your message"<<endl;
}
Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
std::cout << "Your message\n";
}
Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
std::cout << "Your x-y message\n";
}
if(m==n) {
std::cout << "Your m-n message\n";
}
Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.
I don't think that's possible. What you have inside your bracket is a statement which is either true or false, there's no such thing like a true/true or true/false statement. What you could do is a do/while loop with a break statement. But I don't think that's the way to go. Why do you want to avoid two if statements?
single "|" or "&" gaurantees both side evaluation even if the result can be determined by left side operator alone.
You could do something like this, to build up the "message":
string msg = "Your Message\n";
string buildSt = x == y ? m == n ? msg + msg : msg : m == n ? msg : "";
Compiler checks only one condition when both are true because you've connected your conditions with OR.
If even one condition in ORs chain is true there is no need to check others as a result already true and will be false if one of them is false. So if you think that your logic is right then there is no need to do multiple checks. Your code is asking that you will print a message if one of the conditions is true and program doing it. If you want something special for a case when both conditions are true then add it separately. Shortly you should never expect from the compiler to do all checks in the expressions connected by OR.
Regards,
Davit
Tested code:
#include <iostream>
#include <string>
using namespace std;
void main() {
int x=1;
int y=1;
int m=1;
int n=1;
string mess1="Your message 1\n";
string mess2="Your message 2\n";
cout<<((x==y)?mess1:"")+((m==n)?mess2:"");
getchar();
}
If you are trying to see if both statements are true an && is what you will want to use.
Take a look at Boolean Operators to see all of the possible options when comparing boolean (true/false) values.
To answer your question:
if ((x==y) && (m==n))
{
cout<<"Your Message"<<endl<<"Your Message"<<endl;
}
else if((x==y) || (m==n))
{
cout<<"Your Message"<<endl;
}

Why use if-else if in C++?

Why would you use if-else statements if you can make another if statement?
Example with multiple ifs:
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()
Example with else-if:
input = getInputFromUser()
if input is "Hello"
greet()
else if input is "Bye"
sayGoodbye()
else if input is "Hey"
sayHi()
If you have non-exclusive conditions:
if(a < 100)
{...}
else if (a < 200)
{...}
else if (a < 300)
....
this is very different from the same code without the "else"s...
It's also more performant.
In your first example, every if will be checked, even if input is "Hello". So you have all three checks.
In your second example, execution will stop once it found a branch, so if the user types "Hello" it will be only one check instead of three.
The difference may not be much in your simple example, but imagine that you're executing a potentially expensive function and you might see the difference.
you mean like this:
if (a == true && b == false && c == 1 && d == 0) {
// run if true
}
if (a == false || b == true || c != 1 || d != 0) {
// else
}
An else-statement would be much clearer and easier to maintain.
If you need to chose exactly one action from given set of actions, depending on some conditions, the natural and most clear choice is either switch (don't forget to break after each branch) or combination of if and else. When I write
if (conditon1)
{
action1();
}
else if (condition2)
{
action2();
}
else if (conditon3)
{
action3();
}
.
.
.
else {
action_n();
}
it is clear to the reader that exactly one of actions is to be performed. And there is no possibility that because of mistake in conditions more than one action is performed.
Following your same example if we use sequence of if conditions, whatever the input is it will run all 3 conditions. Replacing sequence of if with if-else conditions will run only first condition in best case whereas all 3 in worst case.
So conclude with that if-else will save our running time in most cases, therefore using if-else is preferred over using sequence of if conditions.
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()