Why my or operator doesn't work? - c++

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.

Related

ctype functions(isalpha, isdigit) show wrong values in c++

This is a testing code of my program:
#include <iostream>
#include "ctype.h"
using std::cout;
int main(){
cout << "Welcome to the program: ";
cout << "\n" << "Let's see if the value of \'x\' is digital: ";
int x = 5;
cout << isdigit(x);
cout << "\n" << "Let's see if the value of \'i\' is alphabetical: ";
char i = 'i';
cout << isalpha(i);
return 0;
}
The results:
Welcome to the program:
Let's see if the value of 'x' is digital: 0
Let's see if the value of 'i' is alphabetical: 2
Values like 2 or 0 while both of them are true?
shouldn't it be just 0 or 1 values shown in the results?
Note: I didn't change the values with 'enum' or '#define' in the global variable section.
The isXXX() functions will return an integer representing a true or false value. Given that zero is false and anything else is true, two is a perfectly acceptable return value.
The reason you're getting a false value for isdigit(5) is because that function takes a character and tells you whether it's a digit. While '5' may be a digit character, 5 is most likely not.
C++ defers to C for these functions since they're part of the cctype header. The relevant portion of the standard (C99 7.4) states:
The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF.
The functions in this subclause return nonzero (true) if and only if the value of the argument c conforms to that in the description of the function.
Generally, in C, and in C++ C-legacy functions (a), you should never be comparing a truth value against a fixed true/false value. Since it treats zero as false, everything else as true, the correct way to do it would be something like:
cout << "It " << (isdigit(x) ? "is" : "isn't") << " a digit";
(a) This is usually a good rule to follow, even for C++ bool comparisons (and other languages) where it has to be true or false.
If a boolean value or function is properly named (and it should be), the right way to do it is:
if (! errorOccurred) ...
if (isComplete) ...
if (isdigit(myChar)) ...
That's because, using reductio ad absurdum, the expression boolVal == TRUE is simply another boolean value, so where do you stop?
if (isComplete == TRUE) ...
if ((isComplete == TRUE) == TRUE) ...
if (((isComplete == TRUE) == TRUE) == TRUE) ...
if ((((isComplete == TRUE) == TRUE) == TRUE) == TRUE)...
And so on, ad infinitum.
No, isalpha and isdigit do not return a bool, nor are they required to return 1. They're specified to return a non-zero value if the predicate is satisfied, zero otherwise.

Conditional if statement bug

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?

C++ variable value not changing

I'm using the following code (it's been super simplified to get to the root of my problem).
#include <iostream>
namespace std;
int user;
int submit(int);
int main() {
user = 1;
submit(user);
user = 2;
submit(user);
return(0);
}
int submit(int user) {
if (user = 1) {
printf("1");
} else if (user = 2) {
printf("2");
}
return(0);
}
I thought that this would print out "12" but instead I'm getting "11". Isn't the variable "user" getting redefined before the function is called for the second time?
What's going wrong here?
Use ==, not = to check the values of user. You're overwriting the values (with =) instead of comparing them (with ==).
You are using = not == in your function body.
if (user = 1) { //This assigns user the value of 1 and then prints 1
printf("1");
The correct test condition should be :
if (user == 1) { //This checks the value of user and then prints if the condition is true
printf("1");
While compiling, if using gcc, adding the option -Wall is helpful in such cases as it gives you a warning about assignments in test conditions.
As answered by the experts, You are using = instead of using == in your function body that's why you are getting wrong output.
Here, I would like to clear your concept why it happens:
I hope you know the difference between assignment operator and equality operator. If not, I'm going to describe it briefly.
Assignment operator (=):
The assignment operator assigns a value to a variable. e.g.
user = 1;
This statement assigns the integer value 1 to the variable user.
This statement will always be executed which indicates that it is logically TRUE statement (assuming variable user is declared already).
As there is no comparison or something like that, so if we use Assignment operator(=) as a condition, it will always return TRUE or 1
Equality operator(==):
The equality operator is used to compare two values to know if they are equal or not.
user == 1;
This statement will compare the value of variable user with 1 and it will return TRUE if the value of user is 1 otherwise it will return FALSE.
RESULT: Assignment operator will always return TRUE but comparison operator may return TRUE or FALSE.
Now coming back to your code:
int submit(int user) {
//as you're using assignmnt operator this if condition will always true regardless of input
if (user = 1) {
printf("1");
//because if condition is true, it will never go into else if condition
} else if (user = 2) {
printf("2");
}
return(0);
}
So, actually, whenever you call this function, it will print 1 each time regardless of the value of user passed to this function. Since, you have called this function 2 times. Therefore, it will print 11.

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;
}

Parse error in code: expected ' ; ' before ' { ' token -- what is causing this?

The error I'm getting is error: expected ' ; ' before ' { ' token
I tried fixing the code by adding ; after if (thisisanumber==5) as well as after else (thisisanumber!=5). While this solves the first error it creates another error that says error: ' else ' without a previous ' if '. I'd really love to know what error I've made in writing the code, thanks.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int thisisanumber;
cout<<"Whats the Password?: ";
cin>> thisisanumber;
cin.ignore();
if (thisisanumber==5) {
cout<<"You've discovered the password! Wow, you're a genious you should be proud./n";
}
else (thisisanumber!=5) {
cout<<"You've failed in knowing the password and therefore cannot enter, leave and do not come back. Goodbye!/n";
}
cin.get();
}
You're missing a keyword if:
else if (thisisanumber!=5) {
^^
Alternately, since the opposite condition to thisisanumber == 5 is that thisisanumber is not 5, you don't need the condition:
else {
You don't need another condition as there are only two cases - just use else { ... } and it will catch all cases in which thisisanumber==5 is false.
The structure of an if statement is:
if (condition) { ... }
else if (another condition) { ... }
// ... more conditions
else { ... all cases in which no previous condition matched end up here ... }
... but the else if and else parts are always optional.
What happens is the compiler looks at the following:
else (thisisanumber!=5) {
and thinks to itself:
"OK, here's else. Is the next token if? No. Ok, so this is an else clause, and the next thing is what to do in the else-case. Is the next token {? No. Ok, so in the else-case, we execute a single statement, instead of a block. Is the next token (? Yes. Ok, so our statement is wrapped in parentheses... [insert here: the rest of the thought process for interpreting an expression that's wrapped in parentheses] Ok, there's the matching ). Whew. Now let's just match up the ; for this statement... wait, what's this? A {! That's not right."
The compiler is reading the code one token at a time, left to right. It does not report an error at the point where, in a logical sense that humans understand, the error actually is. It reports an error at the point where, by reading the code one token at a time, left to right, it is first able to detect that something is wrong.
It would be legal to write else (thisisanumber!=5);. That would mean "if the number is not equal to 5 (because the if test failed), then check if the number is not equal to 5, and do nothing with the result of that comparison". Meaningless, but legal. It would also be legal to write else if (thisisanumber!=5) {...}, which is presumably what you meant. That would mean "if the number is not equal to 5 (because the if test failed), and the number is not equal to 5, then do this stuff inside the {}". But this is redundant: given that something is not equal to 5, it is guaranteed to be not equal to 5, so there is no point in specifying the test twice. So we should just write else {...}.
"else" is really a shorter word for "otherwise", and has that purpose in C++ as well.