我需要了解我的程序“检查输入十六进制消息的第三个位置”
- 程序将采用十六进制值输入消息。例如0x0123456789abcdef
- 程序将检查输入消息的第三个位置,即 0
- 现在程序将采用另一条十六进制值的输入消息。例如0x123456789abcdef0
- 这里程序将检查输入消息的第三个位置,即 1
- 程序将采用另一条十六进制值的输入消息。例如x23456789abcdef10
- 这里程序将检查输入消息的第三个位置,即 2
- 程序将采用另一条十六进制值的输入消息。例如0x3456789abcdef210
- 这里程序将检查输入消息的第三个位置,即 3
该过程必须完成 18 次。
每次程序都会检查输入消息的第三个位置。如果输入消息的第三个位置是增量,例如第一个输入消息的第三个位置是 0,第二个输入消息的第三个位置是 1,第三个输入消息的第三个位置是 2,依此类推。然后程序将继续跟踪输入消息并检查输入消息的第三个位置。
如果输入消息的第三个位置不递增,例如第三个输入消息的第三个位置不是 2,那么程序将发送消息并停止。
我尝试编写该程序,但它不起作用。
#include <stdio.h>
#include <stdlib.h>
int main() {
char a[18], b[18], c[18], d[18],e[18], f[18], g[18], h[18];
char value;
char hexmsg[18], nextmsg[18]; /// ={0x0123456789abcdef};
printf(" write the hexmsg \n");
gets(hexmsg);
printf(" \n The Alive Counter is %c \n",hexmsg[2]);
printf(" write the first message \n");
gets(nextmsg);
value= value+hexmsg[2];
int i;
i=value;
while(i<18){
if(i==nextmsg[2]){
printf("OK");
printf(" write the nextmsg \n");
gets(nextmsg);
i++;
}else{
printf("NOT OK");
break; // --> break must to stop the while Loop
}
}
return 0;
}
最佳答案
您主要有四个问题。
- “0x0123456789abcdef”需要 19 个房间。例如 char hexmsg[19];
- 数字和字母不同。例如 0 != '0'
char value;
...value= value+hexmsg[2];
:使用未初始化的变量gets
已过时。你不应该使用它。输入超过缓冲区大小的内容存在危险。
例如,执行如下操作。
#include <stdio.h>
#include <ctype.h>
int main(void){
//input format : 0x0123456789abcdef
char hexmsg[17];// omit 0x, 16 hexdigit chars + 1 for NUL
char line[96], ch;
for(int i = 0; i < 18; ++i){//do 18 times
printf("write the hexmsg>");fflush(stdout);
fgets(line, sizeof line, stdin);//Make room for input acceptance
if(1 != sscanf(line, "0%*1[xX]%16[0-9A-Fa-f] %c", hexmsg, &ch)){
printf("invalid input\n");
--i;//cancel this turn
continue;
}
ch = tolower(*hexmsg);//3rd position of input
if(ch == "0123456789abcdef"[i % 16]){//check hexdigit : 0..9a..f01
puts("OK");
} else {
puts("NOT OK");
break;
}
}
return 0;
}
关于检查输入十六进制消息的第三个位置 --> 在 C 程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40556698/