else if Condition not executing

Hello. This seems to respond correctly by asking follow up questions when pressing Y/y, but when I press N/n it still asks the same questions.

Also, I tried doing:
else if (response == 'N' || 'n') {
return 0;
}
to exit out of program but, that didn't work.

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
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;

int main() {

	char response;
	double inCost = double();
	double downPay = double();
	double finCost, anMortg, loanAm, lnInt, taxSave, intPay;

	loanAm = inCost - downPay;
	lnInt = loanAm * .6;
	anMortg = (loanAm * .3) + (lnInt);
	intPay = anMortg / 12;
	taxSave = lnInt * .35;
	finCost = anMortg - taxSave;

	cout << "Hello. Would you like to calculate the final cost of a house? (Y/N): " << endl;
	cin >> response;

	if (response == 'Y' || 'y') {
		cout << "What is the cost of the house?: " << endl;
		cin >> inCost;

		cout << "What is your down payment?: " << endl;
		cin >> downPay;
	}
		else if (response == 'N' || 'n') {
		cout << "Thank you. Please exit." << endl;
		}


	system("pause");

}
Last edited on
You're going to need a complete statement on BOTH sides of the OR logic operator when using it this way.

1
2
3
if (response == 'Y' || 'y') //incorrect

if (response == 'Y' || response == 'y') //correct 
Last edited on
Operators have precedence. See bottom of http://www.cplusplus.com/doc/tutorial/operators/

1
2
3
4
5
6
7
if (response == 'Y' || 'y')
// means same as
if ( (response == 'Y') || 'y')
// and could be expressed more explicitly as
bool lhs = (response == 'Y');
bool rhs = 'y';
if ( lhs || rhs )

The lhs might be true or false, depending on the 'response'.
The rhs is true.
OR that has at least one true operand is true.


An alternative to testing both lowercase and uppercase is to use first convert to one case: http://www.cplusplus.com/reference/cctype/tolower/
1
2
response = tolower( response );
if ( response == 'y' )
Topic archived. No new replies allowed.