c++ - 在枚举中编写代码

标签 c++

我在中写了一个关于如何访问我的字段的特定方法,但我的老师告诉我我应该使用enum

如何重写此代码以使用 enum 而不是使用 goto

void SetType() {
    cout << "Book SetType" << endl;
    Choice: cout << "Please Select from the list: \n "
            << "1- Technical literature \n "
            << "2- Fiction literature \n "
            << "3- Textbook" << endl;
    int i;
    cin >> i;

    switch (i) {
    case 1:
        Type = "Technical literature";
        break;
    case 2:
        Type = "Fiction literature";
        break;
    case 3:
        Type = "Textbook";
        break;
    default:
        cout << "Erorr you entered a wrong choice" << endl;
        goto Choice;
    }
}

最佳答案

只需使用循环而不是 gotos 它将成为意大利面条代码。 枚举很好,不关心定义的数字,因为如果您添加新的,它们会自动递增。

#include <iostream>
#include <string>
void SetType();

using namespace std;
string Type;
int main()
{
    SetType();

    cout << "so you choose " << Type << endl;
    return 0;
}
enum select
{
    Technical_literature = 1,
    Fiction_literature,
    Textbook
};

void SetType() {
    cout<<"Book SetType"<<endl;
    while(1)
    {
        cout<<"Please Select from the list: \n 1- Technical literature \n 2- Fiction literature \n 3- Textbook"<<endl;
        int i;
        cin >> i;

        switch(i) {
        case Technical_literature:
            Type="Technical literature";
            return;
        case Fiction_literature:
            Type="Fiction literature";
            return;
        case Textbook:
            Type="Textbook";
            return;
        default:
            cout << "Erorr you entered a wrong choice" << endl;

        }
    }
}

关于c++ - 在枚举中编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13479724/

相关文章:

c++ - 使用 std::function 的优点

java - 使用 NewGlobalRef 时的 JNI "local reference table overflow"

c++ - 在放置新分配的对象时不调用析构函数可以吗?

c++ - 将类作为模板参数,并将类构造函数的参数作为方法参数的方法

c++ - 使用 WNDCLASSEX 创建窗口? [Cpp]

c++ - 字符串比较 C++ 中的奇怪行为

c++ - 更新 g++ 但仍然是旧版本

c++ - 使用 MPI_Barrier() 后 MPI_Wtime() 的巨大差异?

c++ - LNK1169 和 LNK2005 错误

c++ - 如果我在头文件中调用函数会发生什么?