hello, i am really new in C programming. This is regarding switch case. How do i limit user input in switch cases?
In this case, after they input 1 or 2, i dont want them to input any other number other than 0. Im still new in loop so any suggestion?

#include <stdio.h>
int number;
char Lunch_Dinner_Set[256] = "Lunch/Dinner Set: \n1 Burger/chicken\n1 drink (medium)\n0. Back to Menu";
char Breakfast_Set[256] = "Breakfast Set:\n1 breakfast\n1 drink (medium)\n\n0. Back to Menu";
char Menu[256]= "\n1. Lunch/Dinner Det\n2. Breakfast Set\n9. exit\nSelect Menu: ";

printf("%s", Menu);
scanf("%d", &number);

{   switch (number){
case 0: printf("%s\n", Menu); break;
case 1:printf("%s\n", Lunch_Dinner_Set); break;
case 2: printf("%s\n", Breakfast_Set); break;
case 9: exit(1); break;
default: printf("Invalid"); break;
} while(
scanf("%d", &number)+

2 Years
Discussion Span
Last Post by Angus_1

Use another do-while loop (ie: use nested do-while loop)



       case 1:
       case 2:



You could use another do while loop inside,as cgeier suggested, or have a prompt and your input getting (I suggest using fgets rather than scanf) and some input validation, along witht some value that it checks for, e.g.

#include <string.h>
#define INT_LEN 10
/*EXTRA_CHARS for /n/0 at end*/
#define EXTRA_CHARS 2
int isValid=0, i;
char input[INT_LEN+EXTRA_CHARS];
do {
    fprintf(stdout,"Enter case value: ");
    */get rid of /n if needed here with a for loop*/
    if(condition you want to check) {
        fprintf(stderr,"Relevant error message here\n");
    elseif (next condition you want to check) {
        fprintf(stderr,"Relevant error message here\n");

    /*more conditional statements here*/

    else {
} while (isValid==0);

and then use strtol or atoi to convert, and do your case statement after the fact, thus it will keep prompting for input until it recieves a valid input from the user.

Also, if you need to check if an input is numeric, I suggest making an isNumeric function, or if you need to check if it is an int make an isInt function and just call said function when needed, it's easier to read that way.

Edited by Angus_1: Most likely you will need to #include <string.h> too

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.