Hello again, another example from my book, this time it's a very simple calculator, on page 103/1100. Cannot seem to figure out why this if statement is not working.
if (op=='+')
cout << "Please enter the two numbers you wish to add: \n"; // <- this is part of the if block
cin >> first_number >> second_number; // <- this is not
cout << first_number << " + " << second_number << " = " << first_number+second_number << endl; // <- neither is this
elseif (op=='-') // <- this was not preceeded by an if block
Remember that an if block stops at the first semicolon. If you want a larger if block, you have to put the code in braces.
1 2 3 4 5 6 7 8
if (op=='+')
{ // <- put it in braces
cout << "Please enter the two numbers you wish to add: \n"; // <- now all of this is part of the if block
cin >> first_number >> second_number;
cout << first_number << " + " << second_number << " = " << first_number+second_number << endl;
}
elseif (op=='-') // <- now this will work, because it's immediately preceeded by an if block.
You could substitute if-else statements for the switch statement.
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
switch ( op )
{
case'+':
cout << "Please enter the two numbers you wish to add: \n";
cin >> first_number >> second_number;
cout << first_number << " + " << second_number << " = " << first_number+second_number << endl;
break;
case'-':
// some code
break;
// ...
default:
cout << "Please enter one of the available operators\n";
break;
}