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