Martin Johnsrud - 3 months ago 17
C++ Question

# Logic operators in if statments

So i am writing a calculator as an exercise in c++, were you first select operators

+
,
-
,
*
or
/
by inputting a, s, m or d. The calculator works fine, except for a filter i set up to respond with an error if the user inputs something other than a, s, m or d. The filter is an if statement:

if(Opperator=='a'||'s'||'m'||'d')
{
//some code
}

else
{
//"Operatorfault"
cout <<"opperatorfeil";
}

Even though the "operator" has other
char
values than those the if statement is suppose to execute, the code within the if statement is still executed. The whole code is below. The outputs and variables are in Norwegian, but i have tried to translate in the comments.

#include <iostream>

using namespace std;

//The calculator function
int Kalkulator(int IN1, int IN2, char Opperator)
{
int Svar;

//Detects witch operator the user choose, and preforms the assigned operation
if(Opperator=='a')
{
Svar=IN1+IN2;
}

if(Opperator=='s')
{
Svar=IN1-IN2;
}

if(Opperator=='m')
{
Svar=IN1*IN2;
}

if(Opperator=='d')
{
Svar=IN1/IN2;
}

//Returns the answer
return Svar;
}

int main()
{
//Input a, s, m or d for addition, subtraction, multiplication or division, respectively
cout <<"Skriv \"a\" for addisjon, \"s\" for subtraksjon, \"m\" for multipliksjon, og \"d\" for divisjon";

cout <<endl;
cout <<endl;

char Opperator;

cin >>Opperator;
cout <<endl;

//Checks if the input is valid
if(Opperator=='a'||'s'||'m'||'d')
{
cout <<"Skriv inn det første tallet du vil gjøre opperasjonen på, trykk derreter enter, og skriv inn det andre";
cout <<endl;
cout <<endl;

int IN1;
int IN2;

cin >>IN1;
cin >>IN2;
cout <<endl;

//"The answer is"
cout << "Svaret er: ";
//Calls the calculator function, and inputs the values it has gathered, then prints the answer
cout <<Kalkulator(IN1, IN2, Opperator);
}

else
{
//"Operatorfault"
cout <<"opperatorfeil";
}

return 0;
}

Answer

This is wrong:

if(Opperator=='a'||'s'||'m'||'d')

you can NOT test for equality (or inequality) like this. The code executes as the equivalent of

if (Operator == (result of boolean ORs))

You have to test for equality individually:

if ((op == 'a') || (op == 's') || etc...)
Source (Stackoverflow)
Comments