I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return ‘5’. But I want to five to be a single char ‘5’.
I thought maybe I could cast to a char in the return. However, I just get rubbish.
I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.
char *digits_conversion[][2]= { {'ap_zero', '0'}, {'ap_one', '1'}, {'ap_two', '2'}, {'ap_three', '3'}, {'ap_four', '4'}, {'ap_five', '5'}, {'ap_six', '6'}, {'ap_seven', '7'}, {'ap_eight', '8'}, {'ap_nine', '9'}, {'ap_star', '*'}, {'ap_hash', '#'}, {NULL, NULL} }; char convert_to_char(const char *digit) { int i = 0; for(i = 0; *digits_conversion[i][1]; i++) { if(strcmp(digits_conversion[i][0], digit) == 0) { return (char) digits_conversion[i][1]; } } return '\0'; } int main(void) { char ch; ch = convert_to_char('ap_five'); printf('Converted digit: %c\n', ch); return 0; }
The simplest fix to your existing code is just to change:
into
However, you might find that changing
digits_conversioninto an array of structures will give you code that is easier to understand and maintain. For example: