I am trying to break up a char by spaces, then perform some conditional logic, but using strcmp on the char * isn't working.
int main(void)
{
char buf[64];
char *cmd;
// assign some space delimited words to buf...
if (strcmp(buf, "somestring junk") == 0) { // this works
// do stuff here
}
cmd = strtok(buf, " ");
if (strcmp(cmd, "somestring") == 0) { // this doesn't work
// do stuff here
}
return 0;
}
I've tried different variations such as "somestring " or "somestring\n" to no success. The code compiles without error or warning. The man pages for strcmp lead me to believe strcmp should work. What am I doing wrong?
It was not working because you have the cmd and buf mixed up in strcmp. The following code should work for you:
#include <stdio.h>
#include <cstring>
int main(void)
{
char buf[64] = "somestring junk";
char *cmd;
// assign some space delimited words to buf...
if (strcmp(buf, "somestring junk") == 0)
{
printf("First strcmp works!\n");
}
cmd = strtok(buf, " ");
if (strcmp(cmd, "somestring") == 0)
{
printf("Second strcmp works!");
}
return 0;
}