n_stckwf
n_stckwf

Reputation: 25

How can I create loop for queue?

This is a queue sample.This is working but when I select the choose 1 I can not select choose 2 anymore I know I need a while loop but I could not do that in the correct way.


    printf_s("? ");
    scanf_s("%d", &choose);

In here I need to add a loop I guess but I could not do that properly.

    while (choose != 3) {    
            switch (choose)
            {
            case 1:
                printf_s("Enter a character:");
                scanf_s("\n%c", &chooseNo);
                add(&startPtr, chooseNo);
                printList(startPtr);
                break;
            case 2:
                if (!Isempty(startPtr)) {
                    printf_s("Enter a character for deleting ");
                    scanf_s("\n%c", &chooseNo);

                    if (delete(&startPtr, chooseNo)) {
                        printf_s("%c deleted.\n", chooseNo);
                        printList(startPtr);
                    }
                    else
                        printf_s("%c could not be found.\n\n", chooseNo);
                }
                else
                    printf_s("List is empty.\n\n");

                break;
            default:
                printf_s("Invalid choose.\n\n");
                menu();
                break;

                printf_s("?");
                scanf_s("%d", &choose);
            }
    }
    return 0;
}

Upvotes: 0

Views: 161

Answers (1)

imperosol
imperosol

Reputation: 578

First of all, don't put all your code in. It's like 100~200 lines, from which a half is useless in order to solve your problem.

Your scanf for editing the value of choose in the loop is in the wrong place.

What happens is :

while (choose != 3) {    
    switch (choose) {
    case 1:
        //code for case 1
        break; // if the user chose 1, the program end the switch statement here
    case 2:
        //code for case 2
        break; // if the user chose 2, the program end the switch statement here
    default: // For any choice but 1 or 2, this part is executed
        printf_s("Invalid choose.\n\n");
        menu();
        break; // For the default case, the switch statement ends here
               // Any code written after this point will not be reached at all

    printf_s("?"); // unreachable code
    scanf_s("%d", &choose); // unreachable code
    }
}

So, just write :

while (choose != 3) {    
    switch (choose) {
        /* Code of your switch statement */
    }
    printf_s("?");
    scanf_s("%d", &choose);
}```

Upvotes: 1

Related Questions