我可以在开关声明中包含cin

时间:2016-10-08 22:19:11

标签: c++ switch-statement cin

我正在编写一个程序,它将给出一个形状区域,我必须创建一个菜单供用户使用开关选择一个形状。所以我的问题是我可以使用switch case或者我必须以不同方式格式化我的代码。

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

    }

4 个答案:

答案 0 :(得分:0)

case 1: cout << "Radius? "<<;您在<<

之后有一个迷路"Radius?"

答案 1 :(得分:0)

是的,您可以在switch语句的情况之后包含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;
    }

答案 2 :(得分:0)

你可以使用枚举和开关完成填充:

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

答案 3 :(得分:0)

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

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

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