Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading