0

when I enter alphabet value or a symbol it will cause infinite loop. is there any solution i can solve this?

int main()
  {
    int input, input2, output;
    printf("ENTER INPUT AS 1 OR 0 (1 AS TRUE AND 0 AS FALSE)");
    printf("\nEnter your first input:");
    scanf("%d", &input);
    while (input != 0 && input != 1)
    {
        printf("Please enter a valid input:");
        scanf("%d", &input);
    }
    printf("Enter your second input:");
    scanf("%d", &input2);
    while (input2 != 0 && input2 != 1)
    {
        printf("Please enter a valid input:");
        scanf("%d", &input2);
    }
    output = input & input2;
    printf("\n\nThe truth table of AND gate with given input is shown below\n\n");
    printf("\t\tTruth Table");
    printf("\n\nINPUT\t\tINPUT2\t\tOUTPUT");
    printf("\n%d\t\t%d\t\t%d", input, input2, output);
    _getch();
  }
VHumFF
  • 1
  • If you think a failed `scanf` removes the "offending" data from your input stream, think again. It's still there, and will fail again, and again... See here [Why is `scanf` causing an infinite loop in this code?](https://stackoverflow.com/questions/1716013/why-is-scanf-causing-infinite-loop-in-this-code). The first mistake is assuming `scanf` worked. It has a return value for a reason; *use it*. And never assume success when it comes to user-input. *Ever*. – WhozCraig Aug 28 '21 at 01:56
  • Your code also has potential undefined behavior. When `scanf` fails the target variables (in your case `input` and `input2`) are left *indeterminate*. You never initialized them either. Therefore, imagine, (a) declare *uninitialized* `input` as you have now, (2) invoke scanf and it fails (like when you enter non-int-compatible data), then (3) testing `input` as you are now in the while condition. *It still has no defined value*. Therefore the test itself is undefined. – WhozCraig Aug 28 '21 at 02:00

0 Answers0