Search code examples
cansi-c

Storing integers of a char pointer in c?


if player1 inputs: "A5-B2" (ranges: A-G 1-7 ) so char * input = "A5-B2" and i want each data to be held like this:

int x1 = 1  (since A should be 1)
int y1 = 5
int x2 = 2 (if A=1, then B=2 and so on)
int y2 = 3

so I realize I can use strtok which separates a5 from b2 but how do i seperate a from 5 and b from 2?


Solution

  • Use sscanf,

    int sscanf(const char *str, const char *format, ...);
    

    In this ,

     sscanf(input,"%c%d-%c%d",&ch1,&int1,&ch2,&int2);
    

    After getting the input in separate variables, for the alphabets use like this.

    int3=ch1-'A' + 1;
    int4=ch2-'A' + 1; 
    

    Ascii value of 'A' is 65. You need that as 1. So subtract by 'A' and add one, store that in the variable it give that as 1 and so on. If that is lower case then subtract with 'a' +1.