0

Apologies for the dumb question, I'm a bit of a beginner and am having trouble understanding why the following code will not work correctly.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int j = ' ';
    int check = 0;

    printf("\nPlease enter A, B, or C\n");
    j = getch();

    while(check == 0)
    {
        if(j != 'A' || 'B' || 'C')
        {
            printf("\nInvalid entry, please enter either an A, B, or C\n");
            j = getch();
        }
        else
        {
            check = 1;
        }
    }
}

All I want this simple program to do is take in either A, B, or C using getch() (Yes, I need to use getch()) and use my while loop to confirm the entry actually is either an A, a B, or a C. However, I run the program, and even when I enter an A, B, or a C, the program tells me my entry is not valid. Can someone help me here and tell me what I'm doing wrong?

I have a feeling this has to do with the fact that it reads in the character as an ASCII integer, but I'm really not sure how to fix this.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Rob Johnson
  • 145
  • 1
  • 1
  • 3
  • Welcome to Stack Overflow. Please read the [About] page soon. Note that `getch()` is a platform-specific function declared in `` on Windows and in `` on Unix (where its use also requires at least one setup function call). However, the use of `getch()` is actually tangential to your problem. – Jonathan Leffler Oct 13 '13 at 22:47

2 Answers2

4
if(j != 'A' || 'B' || 'C')

is equivalent to

if(j != 'A' || 'B' != 0 || 'C' != 0)

Both 'B' and 'C' have non-zero value so the condition will always evaluate true.

I think you want to check that j isn't any of the values listed. If so, the line should be

if(j != 'A' && j != 'B' && j != 'C')
simonc
  • 41,632
  • 12
  • 85
  • 103
0

Do the following replacements:

int j = ' '; /* to */  char j = ' ';

if(j != 'A' || 'B' || 'C') /* to */ if(j != 'A' && j != 'B' && j != 'C')

j = getch(); /* to */ j=getchar();

Also, for getchar() to work, include <conio.h> if required.

Pang
  • 9,564
  • 146
  • 81
  • 122