简体   繁体   English

c中的strcmp字符串和字符数组

[英]strcmp string and character array in c

Here is the code I have. 这是我的代码。 I'm trying to do a string comparison. 我正在尝试进行字符串比较。 A serial input reads what keys are pressed and sets cmd.command to what was typed on the keyboard. 串行输入读取按下的键并将cmd.command设置为在键盘上键入的内容。 Then I take that and do a string comparison to see if it is a command that's within my list. 然后,我将其与字符串进行比较以查看它是否在我的列表内。 What I'm stuck on is the string comparison. 我坚持的是字符串比较。

typedef struct {
    const char *cmd;
    void (*cmdFuncPtr)(void);
}CmdStruct;

typedef struct {
    char command[16];
    char argument[16];
} Command;

Command cmd;

CmdStruct cmdStructArray[] = { {"led",      LEDHandler      },
                               {"relay",    RelayFunction    },  };

void ProcessCommand() {
    for (j = 0; j < sizeof(cmdStructArray)/sizeof(cmdStructArray[0]); j++) {
        if(strcmp(cmdStructArray[j].cmd, cmd.command) == 0) {
            // do stuff
        }
    }
}

If I type in "led", then these two printf statements print the same thing. 如果键入“ led”,则这两个printf语句将打印相同的内容。

printf(cmdStructArray[0].cmd);
printf("%s", cmd.command);

How can I get the string comparison to work? 如何获得字符串比较功能?

Your cmd.command commands likely have hidden trailing whitespace. 您的cmd.command命令可能具有隐藏的尾随空格。 Strip the whitespace before running comparisons. 运行比较之前,请删除空格。 (Thanks David Schwartz in the comments!) (感谢David Schwartz的评论!)

I found a fix, and now strcmp works. 我找到了解决方法,现在strcmp可以了。 I changed the struct in the struct array. 我在结构数组中更改了结构。 Now it's 现在是

typedef struct {
    char cmd[16];
    void (*cmdFuncPtr)(void);
}CmdStruct;

I don't know why this works, and don't know what the difference is. 我不知道为什么这样做,也不知道有什么区别。 The const char *cmd I had before is also a way to create a "string" in C. 我之前拥有的const char * cmd也是在C中创建“字符串”的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM