简体   繁体   中英

Can this if be added to this switch statement?

Hi so I'm building a hotel management program and I'm trying to make my switch statement short but it's not working. I tried to add a function that had the break inside but I get an error saying break not within a loop or a switch statement:

void goback()
{
    char y;
    printf("Would you like to go back?(Y/N)");
    scanf("%c",&y);
    if (y=='Y' || y=='y')
    {
        break;
    }
}
int main(){
    do
    {
        printf (" 1. Add a Room\n 2. Current rooms\n 3. Add a booking\n 4. Current bookings \n 5. Modify a booking\n 6. Print bill\n 7. Exit\n\n");
        printf ("Which section would you like to access:");
        scanf ("%d",&w);
        switch (w){
            case 1:
                clrscr();
                newroom();
                goback();
            case 2:
                clrscr();
                roomscan();
                goback();
            case 3:
                clrscr();
                addbooking();
                goback();
            case 4:
                clrscr();
                currentbooking();
                goback();
            case 5:
                clrscr();
                printf("not ready\n");
            case 6:
                clrscr();
                printf("not ready\n");
            case 7:
                clrscr();
                printf("\t\t\t\tLogging out... See you next time!");
                exit (1);
                break;
            default:
                printf("try again");
        }
    }
    while (w!=7);

}

of course, you got an error because of the break; statement break you from your goback() function and not from case .

As you know each case block must end with break; .

In your case, you must put the break; statement at the end of each case block and you can make the goback() function returning a boolean to decide if you go back or not, but you must define what to do if the user does not want to go back.

I'm not sure but you might want to add breaks after your statements if they are to be executed separately and not in sequence. here I only see your case 7 contains a break, which means all cases until that one will be executed, if that's what you want it's fine, otherwise maybe try something like this

switch (w){
case 1:
    clrscr();
    newroom();
    goback();
    break;
case 2:
    clrscr();
    roomscan();
    goback();
    break;
case 3:
    ...

Here it seems that your goback() function tries to do that break but what it does it's it tries to break from the context where it if called, here an "if" bloc, which can't have a break inside it. That's what the compiler is saying I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM