HOW to back for the beginning if the user press any key except 1 or 2 or 3? [closed]

Use dowhile loop and set the condition to while(L != '1' && L != '2' && L != '3');:

do {
    L = getch();
    switch (L) {
    case '1' :
        system("cls"); 
        printf("111111111111111");
        break;
    case '2' :
        system("cls");
        printf("222222222222222");
        break;
    case '3' :
        system("cls");
        printf("33333333");
        break;
    default :
        sleep(0);
    }
} while(L != '1' && L != '2' && L != '3');

The code above will prompt for data first then evaluate it and continue these until user enters '1', '2' or '3'.


As comments bellow mention the default case with sleep(0) has no use but it can be improved e.g. as follows:

do {
    L = getch();
    switch (L) {
    case '1' :
        system("cls"); 
        printf("111111111111111");
        break;
    case '2' :
        system("cls");
        printf("222222222222222");
        break;
    case '3' :
        system("cls");
        printf("33333333");
        break;
    default :
        L = 0;
    }
} while(!L);

In this example you don’t have to double check for permitted values (assuming that you don’t want to use the case when L == 0).


As the title of your question is a bit misleading maybe I didn’t understand what do you like to achieve. If you just want to suspend going back to the beginning of your loop, you can add an extra getch() after the switch block:

while (1) {
    L = getch();

    switch (L) {
    case '1':
        system("cls"); 
        printf("111111111111111");
        break;
    case '2':
        system("cls");
        printf("222222222222222");
        break;
    case '3':
        system("cls");
        printf("33333333");
        break;
    }

    printf("Press Any Key to Continue...");
    getch();
}

If this still doesn’t answer your question I recommend you to improve it.

Browse More Popular Posts

Leave a Comment