我实际上正在进行一个 p2p 和弦节点项目,当我尝试创建一些命令来收集温度、光线、id 等信息时遇到问题。
static void handle_cmd(volatile char* cmdLine)
{
int i = 0;
volatile char* word[500] = {NULL, NULL, NULL};
while((word[i] = parse_cmd_line(&cmdLine, ' ')) != NULL )
{
//printf("word[%i] = %s\n", i, word[i]);
i++;
}
//Analyse the 3 words :
if(strcmp(word[0], "help") == 0)
{
print_usage();
}
else if(strcmp(word[0], "print") == 0)
{
printf("test print...\n");
}
else if(strcmp(word[0], "temperature") == 0)
{
printf("temperature ");
temperature_sensor();
}
else if(strcmp(word[0], "id") == 0)
{
serial_number();
}
/*else if(strcmp(word[0], "light") == 0)
{
light_sensor();
}*/
else if(strcmp(word[0], "search") == 0)
{
//search_key(arg[1]);
}
else if(strcmp(word[0], "send") == 0)
{
if(strlen(word[1]) == 4)
{
printf("sending %s to %x", word[2], strtoul(word[1], NULL, 16));
send_packet(strtoul(word[1], NULL, 16), word[2]);
}
}
else
{
printf("\nCommand unknown !");
}
printf("command received : |%s|%s|%s|\n", word[0], word[1], word[2]);
}
它适用于帮助
、打印
和id
,但不适用于温度
。我不知道这是 strcmp()
的最大长度问题还是数组 word[]
的大小问题,但是当我尝试使用 >temp
或 temper
它有效。
我想在将来创建更大的命令,例如“发送 xxx 到 xxx”。 谢谢 !
编辑:这里是parse_cmd_line()
。
volatile char* parse_cmd_line(volatile char** cmdLine, char separator) {
volatile char* startOfWord = *cmdLine;
int wordLenght = 0;
while (((*cmdLine)[wordLenght] != separator) &&
((*cmdLine)[wordLenght] != '\0') && (wordLenght < 10))
wordLenght++;
// printf("\nwordLenght = %i", wordLenght);
// printf("\nlettre = %c", (*cmdLine)[wordLenght]);
// If no word was found, return NULL
if ((wordLenght == 0) ||
((wordLenght >= 10) &&
(((*cmdLine)[wordLenght] != '\0') || ((*cmdLine)[wordLenght] != ' '))))
return NULL;
// else cut the word and return it
startOfWord[wordLenght] = '\0';
(*cmdLine) += wordLenght + 1;
return startOfWord;
}
最佳答案
您可以使用strtok()来代替parse_cmd_line()。 strtok()是标准C库中的一个函数,它可以为您分割字符串。
查看如何使用 strtok(),只需输入 man strtok
关于c - strcmp 或数组错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50970575/