Help with logic error

Writing a program that when you type in a letter it would return the corresponding number on a phone. Every letter, number, anything returns the number 2. Any help would be appreciated. Code is as follows:

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
#include <iostream>
using namespace std;
int number (char);

void main ()
{
	char letter;
	int ans;
	while(true)
		{
			cout << "Enter a letter: "; cin >> letter;
			ans = number (letter);
			cout << "Number = " << ans << endl << endl;
	}
}
int number (char letter)
{
	int number;
	
	if ('a' || 'b' || 'c' || 'A' || 'B' || 'C')
		number = 2;
	else if ('d' || 'e' || 'f' || 'D' || 'E' || 'F')
		number = 3;
	else if ('g' || 'h' || 'i' || 'G' || 'H' || 'I')
		number = 4;
	else if ('j' || 'k' || 'l' || 'J' || 'K' || 'L')
		number = 5;
	else if ('m' || 'n' || 'o' || 'M' || 'N' || 'O')
		number = 6;
	else if ('p' || 'q' || 'r' || 's' || 'P' || 'Q' || 'R' || 'S')
		number = 7;
	else if ('t' || 'u' || 'v' || 'T' || 'U' || 'V')
		number = 8;
	else if ('w' || 'x' || 'y' || 'z' || 'W' || 'X' || 'Y' || 'Z')
		number = 9;
	else
		cout << "Invalid number!!!" << endl << endl;
	
	return number;
}
This expression

if ('a' || 'b' || 'c' || 'A' || 'B' || 'C')

is always true.

Maybe you should use parameter letter what do you think?
How is it always true? Sorry if it is a stupid question.
Basically C++ treats anything that is not-zero as "True". You aren't evaluating letter == a || letter == b.... You are basically saying if (TRUE || TRUE || TRUE....)

http://www.cplusplus.com/forum/articles/3483/

There's a link that may help explain it better.
Any integer expression that is not equal to 0 is converted to bool value true. As 'a' is not equal to 0 then the whole expression

'a' || 'b' || 'c' || 'A' || 'B' || 'C'

is converted to true.
Last edited on
Well i think you meant another expression in your function

if ( letter == 'a' || letter == 'b' || letter == 'c' || letter == 'A' || letter == 'B' || letter == 'C')


Last edited on
Thank you guys. The link was helpful, I understand the issue now. I didn't realize for each case you would have to do ==.
You might prefer to use a switch statement for cases like this.

http://cplusplus.com/doc/tutorial/control/
Topic archived. No new replies allowed.