如果player1输入:" A5-B2" (范围:A-G 1-7) 所以 char * input =" A5-B2" 我希望每个数据保持这样:
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
所以我意识到我可以使用strtok将a5与b2分开,但是如何从5中分离a和从2中分离b?
答案 0 :(得分:2)
使用sscanf,
int sscanf(const char *str, const char *format, ...);
在此,
sscanf(input,"%c%d-%c%d",&ch1,&int1,&ch2,&int2);
在单独的变量中输入后,字母表就像这样使用。
int3=ch1-'A' + 1;
int4=ch2-'A' + 1;
'A'
的Ascii值为65.您需要将其作为1.因此减去'A'
并添加一个,将其存储在变量中,将其作为1存储,依此类推。如果是小写,则用'a' +1
减去。
答案 1 :(得分:0)
由于char *
定义了一个字符数组,如果你将用户限制为ASCII然后限制为char * input = "A5-B2"
,你可以直接访问各个字符代码作为数组的元素:
input[0] = 65
input[1] = 53
input[2] = 45
input[3] = 66
input[4] = 50
所有数字均为48-57,大写字母为65-90,小写字母为97-122
根据字符代码所在的范围简单分支并存储您想要的值。
答案 2 :(得分:0)
最简单的方法是将每个字符转换为您想要的整数,因为您的输入具有固定长度和简单格式,大写字母和单个数字。
#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;
}