Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c中存储字符指针的整数?_C_Ansi - Fatal编程技术网

在c中存储字符指针的整数?

在c中存储字符指针的整数?,c,ansi,C,Ansi,如果播放机1输入:“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,但如何区分a和5,b和2?使用sscanf int sscanf(const char *str, const char

如果播放机1输入:“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,但如何区分a和5,b和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

进行减法,因为
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为单位


只需根据字符代码的范围进行分支并存储所需的值。

最简单的方法是将每个字符转换为所需的整数,因为您的输入是固定长度的,格式简单,包含大写字母和单个数字

#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;
}
#包括
int main(){
int-x1,x2,y1,y2;
字符输入[]=“A2-B3”;
x1=输入[0]-“A”+1;/*转换A->1,B->2*/
y1=输入[1]-“0”;/*将ASCII数字字符转换为整数“0”->0*/
x2=输入[3]-“A”+1;
y2=输入[4]-“0”;
如果(x1<1 | | y1<1 | | x2<1 | | y2<1
||x1>7 | x2>7 | y1>7 | y2>7
||输入[2]!='-'){
/*错误:输入无效*/
printf(“无效字符串\n”);
}否则{
printf(“x1=%dy1=%dx2=%dy2=%d\n”,x1,y1,x2,y2);
}
返回0;
}

玩家通常可以输入什么?有超过9的数字吗?多个字母“AC4-D3”?字母:ABCDEFG数字:1234567
strtok()
通常不是一个好的选择,在本例中,几乎没有必要。一个简单的
sscanf()
就足够了,或者您可以检查字符串的长度是否为5个字符,然后简单地将索引0处的字符转换为数字(
str[0]-'A'+1
),将索引1处的数字转换为数字(
str[1]-'0'+1
),以及类似地将索引3和4处的数字转换为整数。如何区分整数和字符?例如,案例A5应该是int x=1和int y=5?不应该是
y2==2
?这是什么
“A5-B2”
?在sscanf()中?