Search code examples
cswitch-statementnew-operator

Can i like allow the user input a char during a nested switch statement?


Like first i ask to user to enter a year, if he entered 2010 then the output will just come out, if he input like 2012 then he need to input a char again, im quite bad at explaining but in anyway i can do it? i am new to c programming.. thank you.. i tried to add printf and scanf in the nested switch statement but it dont work...

This is my code if you can understand ahaha im new to programming ..

#include <stdio.h>

int main() {
    int year;
    char code;
    float cost;
    
    printf("Enter the year : ");
    scanf("%d", &year);
    
    switch (year)
    {
        case 2010:
            cost = 200.50;
        break;
        
        case 2012:
        case 2013:
            switch (code)
            {
                printf("Enter the code : ");
                scanf("%c", &code);
                case 'A':
                case 'a':
                    cost = 89.00;
                    break;
                    
                case 'B':
                case 'b':   
                    cost = 105.90;
                    break;
                    
                default:
                    printf("The code entered is invalid. ");
                    break;
            }
        break;
        
        case 2014:
            cost = 350.30;
            break;
            
        default:
            printf("The year you entered is invalid. ");
    }
    
    printf("The cost is : RM %.2f", cost);
}

Solution

  • Instead of:

        case 2013:
            switch (code)
            {
                printf("Enter the code : ");
                scanf("%c", &code);
                case 'A':
    

    Do:

        case 2013:
            printf("Enter the code : ");
            scanf("%c", &code);
            switch (code)
            {
                case 'A':