Help with program (if statement)

There is something wrong with the commented out portion of the code where the if statement is always running and making the boolean false when it should not be. Is there something wrong with my statement or does anyone have an explanation of why it will not work? My professor has been no help, thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
	bool is_valid_expression = true;
	int first_operand, second_operand;
	float value_of_expression;
	char arithmetic_operator;
	cout << fixed << showpoint << setprecision(2);
	cout << "Enter the first operand [0-100]: " << endl;
	cin >> first_operand;

	cout << "Enter an arithmetic operator (+, -, *, / or %): " << endl;
	cin >> arithmetic_operator;

	cout << "Enter the second operand [0-100]: " << endl;
	cin >> second_operand;

	if ((0 > first_operand || first_operand > 100)
		|| (1 > second_operand || second_operand > 100))
	{
		is_valid_expression = false;
	}

//	if (arithmetic_operator != '+' || '-' || '*' || '/' || '%')
//	{
//		is_valid_expression = false;
//	}

	if (is_valid_expression)
	{
		if (arithmetic_operator == '+')
		{
			value_of_expression = float(first_operand + second_operand);
		}

		if (arithmetic_operator == '-')
		{
			value_of_expression = float(first_operand - second_operand);
		}

		if (arithmetic_operator == '*')
		{
			value_of_expression = float(first_operand * second_operand);
		}

		if (arithmetic_operator == '/')
		{
			value_of_expression = float(first_operand) / float(second_operand);
		}

		if (arithmetic_operator == '%')
		{
			value_of_expression = first_operand % second_operand;
			cout << resetiosflags(ios::fixed | ios::showpoint);
		}
		cout << "The value of the expression is " << value_of_expression << endl;
	}
	if (is_valid_expression == false)
	{
		cout << "The expression that you entered is not valid." << endl;
	}
	return 0;
}

Last edited on
Either
1
2
3
4
5
6
7
// if (arithmetic_operator != '+' || '-' || '*' || '/' || '%')
if( arithmetic_operator != '+' &&  arithmetic_operator != '-' &&
    arithmetic_operator != '*' && arithmetic_operator != '/' &&
    arithmetic_operator != '%' )
{
    is_valid_expression = false;
}


Or, simpler: check if we can find the candidate operator in a string of valid operators
1
2
3
const std::string valid_operators = "+-*/%" ;
// http://en.cppreference.com/w/cpp/string/basic_string/find (4)    
is_valid_expression = valid_operators.find(arithmetic_operator) != std::string::npos ;
Topic archived. No new replies allowed.