【问题标题】:Enum and strings枚举和字符串
【发布时间】:2014-12-30 09:16:31
【问题描述】:
int main()
{     
    enum a {cat, dog, elephant};
    enum a b;

    b=dog;
    if (b==dog) printf("Y"); else printf("N");

    return 0;
}

上面的程序有效。它显示Y。但我认为它不是很有用,所以我想做一些类似的东西,但是用字符串:

int main()
{     
    enum a {cat, dog, elephant};
    enum a b;

    char s[100];
    gets(s);

    b=dog;
    if (b==s) printf("Y"); else printf("N");

    return 0;
}

即使s=="dog",也行不通。

【问题讨论】:

  • 应该是 C 还是 C++?
  • <br> 在 C++ 中工作?
  • No.. 忽略那些
    。它应该在 C 中。
  • 它不会编译,因为您将 char 数组与枚举进行比较。
  • 我删除了那些
    。它们来自 html 代码。

标签: c string enums


【解决方案1】:

试试下面的方法

#include <stdio.h>
#include <string.h>

int main(void) 
{
    enum Animal { cat, dog, elephant };
    char * animal_name[] = { "cat", "dog", "elephant" };
    enum Animal b;
    size_t n;

    char s[100];
    fgets( s , sizeof( s ), stdin );

    n = strlen( s );
    if ( s[n - 1] == '\n' ) s[n - 1] = '\0';

    b = dog;
    if ( strcmp( animal_name[b], s ) == 0 ) printf( "Y\n" ); 
    else printf( "N\n" );

    return 0;
}

如果输入dog那么输出是

Y

在比较字符串之前,您可以将输入的字符串转换为动物名称数组字符串中使用的小写。

或者您可以使用 C# 而不是 C,其中枚举数可以转换为字符串。 :)

【讨论】:

    【解决方案2】:

    它不起作用,因为您将枚举与指针进行比较。

    虽然char s[100] 确实可以保存字符串,但s 只是指向字符串开头的内存位置。换句话说,s 是一个内存块,100 字节长。

    【讨论】:

    • 我知道是什么问题。但我不知道如何创建具有这些功能的程序。枚举一个{“猫”、“狗”、“大象”};不要使用“”。
    • @Abbey:首先回答 Deduplicator 的问题:程序应该是 C 还是 C++?解决方案会有所不同。
    • @MOehm ,我已经从问题中删除了 c++ 标签,因为 OP 在 one of his comments 中提到“它应该在 C 中”
    【解决方案3】:

    你可以玩C preprocessor 的把戏,尤其是X-macros(参见例如this)。

    你可以有一个宏在每只动物上调用一些宏 P

    #define DO_ANIMALS(P) \
      P(cat) \
      P(dog) \
      P(elephant)
    

    然后用它来声明enum

    enum animals_en {
    #define DECLARE_ANIMAL(An) En,
    DO_ANIMALS(DECLARE_ANIMAL)
    };
    

    稍后使用它将字符串s 转换为enum animals_en

    enum animals_en convert_string_to_animal(const char*s) {
    #define CHECK_STRING_ANIMAL(An) if (!strcmp(s, #An)) return An;
    DO_ANIMALS(CHECK_STRING_ANIMAL)
       fprintf(stderr, "bad animal %s\n", s); exit(EXIT_FAILURE);
    } 
    

    您可能想查看使用gcc -Wall -C -E yoursource.c &gt; yoursource.i 获得的预处理表单,然后在生成的yoursource.i 上使用一些编辑器或寻呼机以了解更多其工作原理。

    阅读GNU cpp 的文档,尤其是stringification 和concatenation。

    您还可以改进此代码以生成类似于 the answer from Vlad from Moscow 的内容。

    这些技巧在 C 和 C++ 中都适用,但更像 C。 (在 C++11 中,您宁愿尝试使用模板)。

    【讨论】:

      猜你喜欢
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多