Need code that will repeat prompt Enter value(1,2,e): every time.

  • After input 1, it should do case 1 action and repeat prompt.
  • After input 2, it should do case 2 action and repeat prompt.
  • After input other than 1,2,e, it should print "try again" and repeat prompt.
  • After input e, it should print "exit program" and end.

Error:

If I enter a character, the loop is infinite... how do i fix this?

I've tried a switch statement in a while loop as shown below.

int main() {
    int value;
    printf("%s", "Enter value(1,2,e):");
    scanf_s("%d", &value);

    while (value != 'e') {
        switch (value) {
        case 1:
            printf("You have picked correctly!");
            break;

        case 2:
            printf("You have picked incorrectly!");
            break;

        default:
            printf("try again.");
        }
        printf("%s", "\nEnter value(1,2,e):");
        scanf_s("%d", &value);
    } printf("Exit program");
    getchar();
    getchar();
}

I want my output to be:

Enter value(1,2,e):1 You have picked correctly!
Enter value(1,2,e):2 You have picked incorrectly!
Enter value(1,2,e):3 Try again!
Enter value(1,2,e):e Bye!
*exits program*

2 Answers

0
David Cullen On

If you want to check for letters, you have to allow the user to enter letters:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buffer[81];
    int value;

    while (1) {
        printf("%s", "Enter value(1,2,e):");
        scanf("%s", buffer);
        if ('e' == buffer[0]) {
            break;
        }
        value = atoi(buffer);
        switch (value) {
            case 1:
                printf("You have picked correctly!\n");
                break;

            case 2:
                printf("You have picked incorrectly!\n");
                break;

            default:
                printf("try again.\n");
        }
    }
    printf("Exit program\n");
    return 0;
}

Note

This program does no error checking. This code should not be used in a production environment.

0
ShivYaragatti On

To simply this we can just read value as char instead of integer, so that we can input anything i.e number or characters if and only if you would like to have options "0 to 9" in switch case(below program modified to use chars), if cases are more than 0..9 then program give by @David Cullen is the way.

int main() {
char value;
printf("%s", "Enter value(1,2,e):");
scanf_s("%c", &value);

while (value != 'e') {

switch (value) {
case '1':
    printf("You have picked correctly!");
    break;

case '2':
    printf("You have picked incorrectly!");
    break;

default:
    printf("try again.");

}
printf("%s", "\nEnter value(1,2,e):");
scanf_s("%c", &value);
} 
 printf("Exit program");
 getchar();
 getchar();
}