c - strcmp 或数组错误?

标签 c arrays string-comparison strcmp

我实际上正在进行一个 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[] 的大小问题,但是当我尝试使用 >temptemper 它有效。

我想在将来创建更大的命令,例如“发送 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/

相关文章:

c - 如何通过信号离开无限循环?

c - 链表麻烦

arrays - 有效二维数组的delta数据结构

c# - String.Empty 字符串

c# - 如何从一个字符串中只读取 20 个字符并与其他字符串进行比较?

c - 我将如何使用 fread() 进行部分读取,并在此处获得预期的输出?

c - 在 gcc 中匿名使用预定义的结构?

c - 查找具有最大数量 1 的二维数组的连续行

javascript - 如何计算JavaScript中多个数组的交集?什么是 [等于 : function] mean?

python - 如何在Python中检查2个字符串是否包含相同的字母和数字?