0

I'm fairly new to programming and am stuck on making a simple menu with switch statements as I keep getting an "Error C2360 Initialization of 'total' is skipped by 'case' label". I am not sure why this is happening or how to fix it! Any help/criticism is appreciated :D

#include <iostream>
#include <iomanip>
using namespace std; 

    int main()
    {
        int choice; 
        double a, b;
        
        //MENU
        cout << setw(20) << setfill('-') << "" << "MENU" << setw(20) << setfill('-') << "" << endl; 
        cout << "1. Addition " << endl; 
        cout << "2. Subtraction " << endl;
        cout << "3. Multiplication " << endl;
        cout << "4. Division " << endl;
        cout << endl; 
        //USER INPUT
        cout << "What would you like do do? "; 
        cin >> choice; 
        cout << endl; 
        //SWITCH CASE 
        switch (choice)
        {
        case 1:
            cout << "Enter 2 numbers: ";
            cin >> a >> b;
            long double total = (a + b); 
            cout << "The total is: " << total;
            cout << endl;
        break;
        
        case 2:
            cout << "Enter 2 numbers: ";
            cin >> a >> b;
            long double totalM = (a * b); 
            cout << "The total is: " << totalM;
            cout << endl;
        break; 
        }
    
    
    
        return 0;
    }
  • 1
    My advice is try to reduce the duplication of code. I mean if all 4 options will ask for 2 numbers you don't have to do that in the switch. If all 4 options will print a total which is a long double, you don't need to do that in the switch either. – drescherjm Jan 02 '21 at 01:07

1 Answers1

1

you'll need to place the content of your individual cases within curly braces. This scoping can actually always be done but is only required when you bring new variables to the table.

int i;
switch(i)
{
    case(1):
    {
         int newVariable;
         // ... do stuff
    }
    break;
}
Rinzler
  • 39
  • 3