Home > Mobile >  Why aren't some of the case permutations of a 4 letter word using an array of strings working?
Why aren't some of the case permutations of a 4 letter word using an array of strings working?

Time:04-30

I have an array of all some permutations of the word exit in different cases and some of the time it works and some of the time it doesn't. What am I missing?

// Define all possible case permutations of exit
    char *exitStrings[16] = {
        "exit",
        "exiT", 
        "exIt", 
        "eXit",
        "exIT",  
        "eXiT", 
        "eXIt", 
        "eXIT",
        "EXIT", 
        "Exit",
        "EXit",
        "ExIt",
        "ExiT",
        "EXiT", 
        "EXIt", 
        "ExIT"};

    // read the message from client and copy it in buffer
    read(sockfd, buff, sizeof(buff));

    // if read message is one of the permuations of exit strings
    //    exit client
    for (int i = 0; i < sizeof(*exitStrings); i  )
    {
      if (strncmp(buff, exitStrings[i], 4) == 0)
      {
        printf("Client Exit and the Connection is still open\n");
        printf("Listening for new client...\n");
      }
    }

tia

CodePudding user response:

You can transform the input to lowercase and then compare it to "exit" :

#include <ctype.h>

for(int i = 0; buff[i]; i  )
{
     buff[i] = tolower(buff[i]);
}

if (strncmp(buff, "exit", 5) == 0)
{
    printf("Client Exit and the Connection is still open\n");
    printf("Listening for new client...\n");
 }

CodePudding user response:

seems my original code did not have 1 of the 16 cases I originally counted and I figured out how to compare without case sensitivity. Thanks for all of your help

// read the message from client and copy it in buffer
    read(sockfd, buff, sizeof(buff));

    if(strncasecmp(buff, "exit",4)==0)
    {
      printf("Client Exit and the Connection is still open\n");
      printf("Listening for new client...\n");
    }
  •  Tags:  
  • c
  • Related