我可以在switch语句中包含cin吗?

Can I include cin within a switch statment

本文关键字:cin 包含 switch 语句 我可以      更新时间:2023-10-16

我正在编写一个程序,将给出一个形状的面积,我必须创建一个菜单,让用户选择使用开关的形状。所以我的问题是,我可以有cin与开关的情况下,或者我必须格式我的代码不同。

#include <cmath>
    #include <iostream> 
    #include <cassert>
    using namespace std;
    int main()
    {
    int shape, invalid;
    double area, radius, width, height;
    const double pi=3.14159;
    cout << "Shape Menu"<<endl<< "1. Circle"<<endl<<"2. Rectangle"<<endl<<"3. Triangle"<<endl
    <<"shape (1, 2, or 3)? ";
    cin >> shape;

        switch (shape){
            case 1: cout << "Radius? "<<;
            cin >> radius >> endl;break;    // this is were my error is when I compile 
            case 2: cout << "width? ";
            cin >> width >> endl;
            cout << "Height? ";
            cin >> height >> endl;break;
            case 3: cout<< "Base? ";
            cin >> base >> endl;
            cout << "Height? ";
            cin >> height >> endl;break;
            default: invalid = shape 
            cout<< shape << "is an invalid menu option, program terminated."<<endl;
            assert (invalid == T)
        }

        return 0;
    }

case 1: cout << "Radius? "<<;"Radius?"之后有一个流浪的<<

可以在switch语句的case后面包含cin。像case 1:这样的案例只是标签。所以后面的指令可以是任何指令

你的代码有很多编译错误:这里有一个可能的替换你的switch语句。

    switch (shape){
        case 1: cout << "Radius? ";
        cin >> radius;break;    // no more error here 
        case 2: cout << "nwidth? ";
        cin >> width;
        cout << "nHeight? ";
        cin >> height;break;
        case 3: cout<< "Base? ";
        cin >> base;
        cout << "nHeight? ";
        cin >> height;break;
        default:
        invalid = shape;
        cout<< shape << "is an invalid menu option, program terminated."<<endl;
    }

您可以使用enum填充并切换:

#include <iostream>
enum SHAPES{CIRCLE = 1, SQUARE, RECTANGLE, TRIANGLE, CUBE};

int main()
{
    int choice;
    std::cout << "1: Circle  2: Square  3: Rectangle  4: Triangle  5: Cube" << std::endl;
    std::cout << " >> ";
    std::cin >> choice;
    std::cout << std::endl;
    switch(choice)
    {
        case CIRCLE:
        {
            //do something
        }
        break;
        case SQUARE:
        {
            //do something
        }
        break;
        case RECTANGLE:
        {
            //do something
        }
        break;
        case TRIANGLE:
        {
            //do something
        }
        break;
        case CUBE:
        {
            //do something
        }
        break;
        default:
            std::cout << "Bad Entry!" << std::endl;
    }
    std::cout << std::endl;
    return 0;
}

当然可以在switch语句中使用cin。没有这样的界限。由于代码中有许多其他语法错误的语句,因此会出现错误。检查@Franck的答案,因为他已经纠正了他们。如果你想了解更多关于Switch语句的信息。这些都是很好的参考资料。

https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm

http://www.programiz.com/cpp-programming/switch-case