Search code examples
cwhile-loop

Infinite C while loop


enter image description here

while (option){
        printf("\nPress 0 : Exit\nPress 1 : Enqueue\nPress 2 : Dequeue\nPress 3 : Peek\nPress 4 : Isempty\nPress 5 : Isfull\nPress 6 : Size\nPress 7 : Display\n");
        scanf("%d", &option);

        if(option == 1){
            Enqueue();
        }else if(option == 2){
            Dequeue();
        }else if(option == 3){
            Peek();
        }else if (option == 4){
            Isempty();
        }else if(option == 5){
            Isfull();
        }else if(option == 6){
            Size();
        }else if(option == 7){
            Display();
        }else if(option == 0){
            printf("\nBYE\nBYE\nBYE");
        }else{
            printf("\nWRONG INPUT!!");
        }
    }

Why is that every time I enter anything except 0 to 7, this while loop starts running infinitely ?


Solution

    • I suggest to read the input as a string and handle incorrect input yourself.
    • switch case is more suitable.
    • change the loop
        int option;
        char str[32];
        
        do{
            option = 0;
            printf("\nPress 0 : Exit\nPress 1 : Enqueue\nPress 2 : Dequeue\nPress 3 : Peek\nPress 4 : Isempty\nPress 5 : Isfull\nPress 6 : Size\nPress 7 : Display\n");
            if(fgets(str, sizeof(str), stdin))
            {
                if(sscanf(str, "%d", &option) != 1) option = 100;
            }        
            switch(option)
            {
                case 1:
                    //Enqueue();               
                    break;
                case 2:
                    //Dequeue();
                    break;
                case 3:
                    //Peek();
                    break;
                /* more options */
                case 0:
                    printf("\nBYE\nBYE\nBYE");
                    break;
                default:
                    printf("\nWRONG INPUT!!");
                    break;
            }
    
        }while (option);
    }