Help! Operator Variable in an IF Statement!

Hi. I'm making a basic maths quiz in which a random operator is chosen along with two random integers. The random operator is chosen by an if statement. A random number between 1 and 2 is generated and if its a 1, the operator variable will be a +. If the generator results in a 2, the operator variable will be set to -.

In the code below, the user inputs an answer to a previously asked math question. valueone and valuetwo are both randomly generated. Setoperator is the char variable which stores either the - or the +. However, this results in an error. Help would be appreciated!


 
  if (ans == valueone setoperator valuetwo)
First thing is that above statement is syntactically wrong.

One way of doing this is, You can use macro:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define valueone 5
#define setoperator +
#define valuetwo 3

int main()
{
	int ans=8;
	if(ans == valueone setoperator valuetwo)
	{
		cout<<"Equal"<<endl;
	}
	else
		cout<<"Not-Equal"<<endl;
}


Second way if you want to take valueone,valuetwo and setoperator as a variable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int valueone;
	int valuetwo;
	char setoperator;

	cout<<"\nEnter value one : ";
	cin>>valueone;
	cout<<"\nEnter value one : ";
	cin>>valuetwo;
	cout<<"\nEnter value one : ";
	cin>>setoperator;

	int ans=8;
	if( setoperator == '+' )
	{
		if(ans == valueone + valuetwo)
		{
			cout<<"Equal"<<endl;
		}
	}
	else
		cout<<"Not-Equal"<<endl;

The thing is im using codeblocks which results in the code being run as a .exe in the command prompt area. I cant really enter the values of valueone and valuetwo since it's a random quiz. setoperator is also random so i cant set that as a + or - from the get go. A while command is used as a loop so each number is used multiple times.
Is it possible to store an operator in a variable and call it in an if statement?
Directly you can not do it.

But you know the list of operator right... which can be use or randomly generated.

So take it as in char variable and you can do it like above code doing.

Is it possible to store operators ...

Yes. "Function objects" is the keyword that you should search with.
Topic archived. No new replies allowed.