Enumeration and Strings

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

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

    return 0;
}

The program above works. He is showing Y. But I do not find this very useful, so I want to do something similar, but with the lines:

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

Even if s=="dog", it does not work.

-2
source share
3 answers

Try the following approach

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

If you enter dog, the output will be

Y

Also, before comparing strings, you can convert the entered string to lowercase, which is used in the strings of the array of animal names.

Or you can use C # instead of C, where enumerations can be converted to strings. :)

0
source

This does not work because you are comparing an enumeration with a pointer.

char s[100] , s . , s - 100 .

0

C 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 > yoursource.i, - yoursource.i, , .

Read the GNU cpp documentation , especially stringification and concatenation .

You can also improve this code to generate something similar to Vlad’s answer from Moscow .

Such tricks will work both in C and C ++, but more C-like. (In C ++ 11, you prefer to have templates).

0
source

Source: https://habr.com/ru/post/1569405/


All Articles