Mr PC Mr PC - 26 days ago 5
C Question

switch does not do what I want it to do

My Task is a simple Boolean Calculator



I want to make a simple boolean calculator, which uses OR, AND, NAND and XOR. This is what it has to do:

If the user enters a string starting with
q
(like
quit
) at any time, the program should immediately exit. If the user enters a string starting with
c
(like
cancel
) at any time, the program should abort the current calculation and ask for the first argument again. If the user enters anything other than a
0
, a
1
, or a string starting with
c
or
q
, you should display an error (see below) and ask for the same value again.

Now, I know this is probably very silly, but I really have started right now programming...

It doesn't matter what I enter, it only retuns the "You chose to quit!"
Why does it "ignore" the switch?

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

int main() {
// Declaration Part
char user_input[100];

//Main Body
gets(user_input);
while (user_input[0] == !'q') {
switch (user_input[0]) {
case '0':
case '1':
printf("You chose boolean algebra! \n");
break;
case 'c':
printf("%s\n", "You chose to continue!");
continue;
}
}
printf("You chose to quit! \n");
return 0;
}

Answer

There are 2 major problems in your code:

  • The condition while (user_input[0] == !'q') should be written while (user_input[0] != 'q')

  • The obsolete function gets() should never be used. Use fgets() instead.

  • You do not read a new line in the while loop... the condition is constant, you have either an infinite loop (if you type enter directly) or one you never enter.

Here is a better version:

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

int main(void) {
    // Declaration Part
    char input[100];

    //Main Body
    while (fgets(input, sizeof input, stdin) != NULL && input[0] != 'q') {
        switch (input[0]) {
          case '0':
          case '1':
            printf("You chose boolean algebra! \n");
            break;
          case 'c':
            printf("%s\n", "You chose to continue!");
            continue;
        }
    }
    printf("You chose to quit!\n");
    return 0;
}