0

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?

5
  • what can the player input in general? any numbers > 9? multiple letters "AC4-D3"? Jan 12, 2015 at 4:46
  • Letters: ABCDEFG Numbers: 1234567 Jan 12, 2015 at 4:48
  • strtok() is often not a good choice, and in this example, is pretty much unnecessary. A simple sscanf() would suffice, or you can check that the string is 5 characters long and simply convert the character at index 0 to a number (str[0] - 'A' + 1), the digit at index 1 to a number (str[1] - '0' + 1), and similarly at indexes 3 and 4. Jan 12, 2015 at 4:52
  • How do you seperate ints from chars? such as the case A5 should be int x = 1 and int y = 5 ? Jan 12, 2015 at 4:53
  • 2
    Shouldn't y2 == 2?
    – Bill Lynch
    Jan 12, 2015 at 5:36

3 Answers 3

2

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.

1
  • What is this "A5-B2"? in sscanf()?
    – Gopi
    Jan 12, 2015 at 5:08
0

Since char * defines a character array, if you are limiting the user to ASCII then for char * input = "A5-B2", you could directly access the individual character codes as elements of the array:

input[0] = 65
input[1] = 53
input[2] = 45
input[3] = 66
input[4] = 50

All digits fall withing 48-57, capital letters in 65-90 and lowercase letters in 97-122

simply branch based on the range in which the character code falls and store your desired value.

0

The simplest method is to convert each character to the integers you want because your input is of a fixed length and simple format with capital letters and single digits.

#include <stdio.h>

int main() {
    int x1, x2, y1, y2;
    char input[] = "A2-B3";

    x1 = input[0] - 'A' + 1; /* convert A -> 1, B -> 2 ... */
    y1 = input[1] - '0';     /* convert ASCII digit characters to integers '0' -> 0 ... */
    x2 = input[3] - 'A' + 1;
    y2 = input[4] - '0';

    if (x1 < 1 || y1 < 1 || x2 < 1 || y2 < 1
       || x1 > 7 || x2 > 7 || y1 > 7 || y2 > 7
       || input[2] != '-') {
       /* error: invalid input */
       printf("Invalid string\n");
    } else {
       printf("x1=%d y1=%d x2=%d y2=%d\n", x1, y1, x2, y2);
    }
    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.