0

The code just keeps accepting input and doesn't go on to the if logic and i have no idea why

    while (1){

    // get command
    char cmd[6];
    scanf("%s", cmd);

    if (cmd == "exit"){
        return 0;
    } else if(cmd == "task\n"){
        taskHandler();
    } else if(cmd == "event"){
        eventHandler();
    } else if(cmd == "show"){
        showItems();
    }
}
itsAMC
  • 11
  • 2

2 Answers2

2

In C you can't use == to compare strings, as that would compare the value of the pointer, i.e. the location in memory that has the string data. If you want to compare the actual data, you have to use strcmp, i.e:

if(cmd == "exit") {
  ...
}

should be

if(strcmp(cmd, "exit") == 0) {
  ...
}

int strcmp(const char* str0, const char* str1) returns whether str1 is lexicographically less than, equal to, or greater than (-1, 0, and 1 respectively), so if it returns 0, then str0 and str1 are equal.

I'd also use break instead of the return 0 and move the return 0 to outside of the while(1) loop.

reeeee
  • 139
  • 10
0

In c language you can't use == operator to compare two string. Instead you should use strcmp function to compare two string. See this link.

parsa2820
  • 570
  • 4
  • 13