problem with simple conditional

I'm about at my wit's end here. All I'm trying to do is get this function to work. Every time it hits it, it'll go through the if statement whether or not the condition in parenthesis is true. I know there's something small I'm missing. Any help? I've also tried it as a while loop, and that just keeps providing the error message I wrote it to and asking for the input infinitely.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
char questionTry()
{
   char attempt;

   cout << "Your choice? > ";
   cin >> attempt;

   if (attempt != 'A' || attempt != 'B' || attempt != 'C' || attempt != 'D' ||
       attempt != 'a' || attempt != 'b' || attempt != 'c' || attempt != 'd')
   {
      cout << "That is not a valid answer. Please try again > ";
      cin >> attempt;
   }

   return attempt;
}
Last edited on
Edit: Nevermind.
Last edited on
1
2
if (attempt != 'A' && attempt != 'B' && attempt != 'C' && attempt != 'D' &&
       attempt != 'a' && attempt != 'b' && attempt != 'c' && attempt != 'd')


whether or not the condition in parenthesis is true.

As you wrote it, the condition was always true.
Last edited on
The condition
1
2
 if (attempt != 'A' || attempt != 'B' || attempt != 'C' || attempt != 'D' ||
       attempt != 'a' || attempt != 'b' || attempt != 'c' || attempt != 'd')   
is always TRUE !!!

Solution : Replace each || with && .
Also, consider replacing the if statement for a while loop, so the user never enters a wrong choice.
Consider this piece of code :
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

#include <iostream>
using namespace std;

char questionTry()
{
   char attempt;

   cout << "Your choice? > ";
   cin >> attempt;

   while (attempt != 'A' && attempt != 'B' && attempt != 'C' && attempt != 'D' &&
       attempt != 'a' && attempt != 'b' && attempt != 'c' && attempt != 'd')
   {
      cout << "That is not a valid answer. Please try again > ";
      cin >> attempt;
   }

   return attempt;
}

int main()
{
     char ans;
     ans = questionTry();
     std::cout<<ans;
     return 0;
}
Topic archived. No new replies allowed.