【问题标题】:Can we store string in enum data type in C++?我们可以在 C++ 中以枚举数据类型存储字符串吗?
【发布时间】:2021-11-05 06:05:31
【问题描述】:
#include <iostream>
using namespace std;


int main() {
    enum month
    {
         Jan = "Enumeration",
         Feb = "is",
         Mar = "a",
         Apr = "user",
         May = "defined",
         Jun = "datatype",
         Jul = "in",
         Aug = "C/C++",
         Sep = "language",
         Oct = "It",
         Nov = "is",
         Dec = "used"
    };
    month mt = Oct;
    cout<<mt;
    return 0;
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读the help pages,接受SO tour,阅读How to Ask,以及this question checklist
  • 不,枚举只是整数。
  • 还有一点吹毛求疵:没有像“C/C++”这样的东西。请不要使用这个词。尽管它们看起来很相似,但 C 和 C++ 是两种非常不同的语言。
  • ...但是 C 和 C++ 都不支持将其他任何东西作为整数类型来定义 enum 值。仅供参考:Enumerations in C++, Enumerations in C

标签: c++ data-structures


【解决方案1】:

是的,您可以根据这些条件将字符串存储在 C++ 中的枚举类型中:

(1.) 字符串是枚举常量

(2.) 字符串不应包含在引号中。它们应该“按原样”写

根据您的示例,您可以这样做:

#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare the enum type for the months
enum months {January, November};

// List the months
switch(November)
    {
    case January:
     cout << "The first month of the year";
     break;

    case November:
     cout << "The current month when this question was asked and answered.";
     break;

    default:
    cout << "Other months besides January and November";
     break;
    }
    return 0;
}

要查看更多示例(代码实现),请查看:

(1.)https://en.cppreference.com/w/c/language/enum

(2.) https://www.chukwuemekasamuel.com/CPlusPlus/cplusplus.html#module5(滚动直到看到 Switch 语句)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多