Home > Mobile >  How to retrieve an enum index value based on char array? in C (cpp)
How to retrieve an enum index value based on char array? in C (cpp)

Time:09-22

Disclaimer: New to programming, learning on the fly. This is my first post and apologize if the question is not written clearly.

I am trying to go through a tutorial on building a chess engine, but it is written in C and I am attempting to convert it to C code. The idea of the code is to enter a char and retrieve the index value of an enum. I am getting a compile error because of this code. How do I approach this as it isn't clear to me after trying different ideas.

E.g. std::cout << CHAR_TO_PIECE['k']; with expected output of 11.

in "typedefs.h"

enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};

in "board.h"

extern const int CHAR_TO_PIECE[];

and in board.c

// convert ASCII character pieces to encoded constants
int CHAR_TO_PIECE[] = {
    ['P'] = P,
    ['N'] = N,
    ['B'] = B,
    ['R'] = R,
    ['Q'] = Q,
    ['K'] = K,
    ['p'] = p,
    ['n'] = n,
    ['b'] = b,
    ['r'] = r,
    ['q'] = q,
    ['k'] = k
};

CodePudding user response:

You can write a function to return specific enum for you char input .

enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};

Piece charToPiece(char ch)
{
    switch (ch) {
        case 'P':
            return P;
        case 'N':
            return N;
        case 'B':
            return B;
        case 'R':
            return R;
        case 'Q':
            return Q;
        case 'K':
            return K;
        case 'p':
            return p;
        case 'n':
            return n;
        case 'b':
            return b;
        case 'r':
            return r;
        case 'q':
            return q;
        case 'k':
            return k;
    }
}

CodePudding user response:

A more C way to handle this is to use a std::map (or std::unordered_map), eg:

#include <map>

enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k};

extern const std::map<char, Piece> CHAR_TO_PIECE;
// convert ASCII character pieces to encoded constants
const std::map<char, Piece> CHAR_TO_PIECE = {
    {'P', P},
    {'N', N},
    {'B', B},
    {'R', R},
    {'Q', Q},
    {'K', K},
    {'p', p},
    {'n', n},
    {'b', b},
    {'r', r},
    {'q', q},
    {'k', k}
};
std::cout << (int) CHAR_TO_PIECE['k'];

CodePudding user response:

You can create an array of enums with 2 x 26 entries (upper and lowercase), and assign every relevant entry the correct enum. This must be coded manually. With such a correspondence table, character lookup is immediate. (You can also reserve a "unassigned" value if needed.)

  • Related