所以现在我的结构定义如下:
typedef struct rec_msg {
uint8_t unit[4];
uint8_t subdevice[4];
uint8_t command[4];
uint16_t data[3];
uint16_t msg_id[1];
} rec_msg;
...我想读取struct中的字符数组,然后根据它们运行命令。现在我这样做了,看起来似乎会有更清洁的方法。
if (strncmp((const char *)message->unit, "blah", 3) == 0)
{
if (strncmp((const char *)message->subdevice, "syr", 3) == 0)
{
if (strncmp((const char *)message->command, "rem", 3) == 0)
{
// run some command
}
else if (strncmp((const char *)message->command, "dis", 3) == 0)
{
// run some command
}
else
{
DEBUG_PRINT("Message contains an improper command name");
}
}
else if (strncmp((const char *)message->subdevice, "rot", 3) == 0)
{
if (strncmp((const char *)message->command, "rem", 3) == 0)
{
// run some command
}
else if (strncmp((const char *)message->command, "dis", 3) == 0)
{
// run some command
}
else
{
DEBUG_PRINT("Message contains an improper command name");
}
}
else
{
DEBUG_PRINT("Message contains an improper subdevice name");
}
}
else
{
DEBUG_PRINT("Message contains the wrong unit name");
}
}
答案 0 :(得分:1)
而不是一般问题的显式代码,将任务分解为步骤。伪代码如下。
对于3组字符串中的每一组,将匹配的文本转换为数字。建议一个带有相应枚举的字符串数组。 (2如下所示)
enum unit_index {
unit_blah,
unit_N
};
const char *unit_string[unit_N] = {
"blah"
};
enum subdevice_index {
subdevice_syr,
subdevice_rot,
subdevice_N
};
const char *subdevice_string[subdevice_N] = {
"syr"
"rot"
};
查找匹配的索引
unit_index unit = find_index(message->unit, unit_string, unit_N);
if (unit >= unit_N) {
DEBUG_PRINT("Message contains the wrong unit name");
return FAIL;
}
subdevice_index subdevice = find_index(message->subdevice, subdevice_string, subdevice_N);
if (subdevice >= subdevice_N) {
DEBUG_PRINT("Message contains the wrong subdevice name");
return FAIL;
}
// similar for command
现在代码有3个索引对应3个文本字段。
创建索引表和相应的命令
typedef struct {
enum unit_index unit;
enum subdevice_index subdevice;
enum command_index command;
int (*func)();
} index2func;
index2func[] = {
{ unit_blah, subdevice_syr, command_dis, command_blah_syr_dis },
{ unit_blah, subdevice_rot, command_dis, command_blah_rot_dis },
...
{ unit_blah, subdevice_rpt, command_rem, command_blah_rot_rem }
};
在表格中找到一组匹配的索引并执行命令。