Struggling to end loop comparing strings

67 views Asked by At

I am attempting to create a C program that compares a string input with 3 valid strings, if the input isnt the same as any of the strings then it will reloop. Howver I cannot make the loop close even when the user input is valid

char HB[3] = "HB";
char FB[3] = "FB";
char BB[3] = "BB";
int x = strcmp(boardType, FB);
int y = strcmp(boardType, BB);
int z = strcmp(boardType, HB);
do {
    fflush(stdin);
    printf("Which board type would you like? Full Board(FB), Half Board(HB) or Bed & Breakfast(BB)\n");
    scanf("%s", &boardType);
    printf("%s", boardType);
} while (x != 0 || y != 0 || z != 0);

It keeps the loop running even when HB, BB or FB are entered

1

There are 1 answers

4
John Doe On

You never change the values of x, y and z inside the loop, the comparison in never done for new values read from the user.

Also you need to use && instead of ||, otherwise even if you input the right value for one of the board types the others will be different so the or check will loop anyway.

Try to move the strcmp inside the loop (I'm assuming that boardType is declared somewhere on top and you omitted it for brevity)

char HB[3] = "HB";
char FB[3] = "FB";
char BB[3] = "BB";
int x = 1;
int y = 1;
int z = 1;
do {
    fflush(stdin);
    printf("Which board type would you like? Full Board(FB), Half Board(HB) or Bed & Breakfast(BB)\n");
    scanf("%s", &boardType);
    printf("%s", boardType);
    x = strcmp(boardType, FB);
    y = strcmp(boardType, BB);
    z = strcmp(boardType, HB);
} while (x != 0 && y != 0 && z != 0);

If the comparison is done outside the loop the variables will never change so it doesn't matter what the user inputs, their value always going to be equal to the one they had the first time the loop is run.