无限 C while 循环

问题描述 投票:0回答:1

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!!");
        }
    }

为什么每次我输入除 0 到 7 之外的任何内容时,这个 while 循环都会开始无限运行?

c while-loop
1个回答
0
投票
  • 我建议先阅读字符串。
  • switch case
    比较合适。
  • 改变循环
    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(32), 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.