skip to Main Content

I am new to C++ and I am stuck on the switch statement because it doesn’t seem to give an output when the value in the parentheses is an integer (Console-Program ended with exit code: 0). Although, the same code works fine when I change the type to char.
Thank You.

int main()
{
    int num1;          // argument of switch statement must be a char or int or enum
    
    cout<< "enter either 0 or 1" << "n";
    cin>> num1;
    
    switch (num1)
    {
        case '0':
            cout<< "you entered 0" << endl << endl;
            break;
            
        case '1':
            cout<< "you entered 1" << endl << endl;
            break;
            
    }
    
}

2

Answers


  1. You are switching on an int, which is correct, but your cases are not integers – they are char since they are surrounded in '.

    ‘0’ is never equal to 0, nor is ‘1’ ever equal to 1.

    Change the case values to integers.

    int main()
    {
        int num1;
        
        cout<< "enter either 0 or 1" << "n";
        cin>> num1;
        
        switch (num1)
        {
            case 0:
                cout<< "you entered 0" << endl << endl;
                break;
                
            case 1:
                cout<< "you entered 1" << endl << endl;
                break;
                
        }
        
    }
    
    Login or Signup to reply.
  2. int main()
    {
        int num1;          // argument of switch statement must be a char or int or enum
        
        cout<< "enter either 0 or 1" << "n";
        cin>> num1;
        
        switch (num1)
        {
            case 0:
                cout<< "you entered 0" << endl << endl;
                break;
                
            case 1:
                cout<< "you entered 1" << endl << endl;
                break;       
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search