具有整数值的 Switch 语句

Switch statement with integer value

我是 C++ 的新手,我被 switch 语句卡住了,因为当括号中的值为整数时它似乎没有给出输出(控制台程序以退出代码结束:0)。虽然,当我将类型更改为 char 时,相同的代码工作正常。 谢谢。

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;
            
    }
    
}

您正在打开 int,这是正确的,但您的个案不是整数 - 它们是 char,因为它们被包围在 '.

“0”永远不会等于 0,“1”也永远不会等于 1。

将大小写值更改为整数。

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;
            
    }
    
}
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;       
    }

}