1

I'm not sure what my title should be. But, I was trying to get a nice validation for my code. Below are the only codes allowed to go in my function: c0001, c0002, c0003, c0004, c0005, C0001, C0002, C0003, C0004, C0005. So, other than these 10 codes, it should not accept it and keep promoting the user for a correct code.

if (strlen(meal_choice) == 5 && (meal_choice[0] == 'C' || meal_choice[0] =='c') && meal_choice[1] == '0' && meal_choice[2] == '0' && meal_choice[3] == '0' && (meal_choice[4] == '1' || meal_choice[4] == '2' || meal_choice[4] == '3' || meal_choice[4] == '4' || meal_choice[4] == '5'))

As you can see from my code above, it's way too long. Any idea how I can shorten my code? Thanks!

Michelle Ler
  • 55
  • 1
  • 7

2 Answers2

2

You can check that a character is a digit in a certain range you can compare the character to endpoints of the range with >= and =<, because digits are assigned consecutive codes:

... && meal_choice[4] >= '1' && meal_choice[4] <= '5'

You can also use sscanf's rudimentary regex-like capabilities for validation, like this:

int res = -1;
sscanf(code, "%*[cC]000%*[1-5]%n",  &res);
if (res == 5) {
    ... // The code is valid
}

The above scans and ignores formatted input (note asterisks after percentage signs), and reads the number of processed characters with %n. If all five characters are processed, the input is considered valid.

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

In my humble opinion this is the most readable code, which is the most important aspect you should aim for:

const char* valid_codes[] = {
    "c0001", "c0002", "c0003", "c0004", "c0005",
    "C0001", "C0002", "C0003", "C0004", "C0005"
};

const int valid_codes_size = sizeof(valid_codes) / sizeof(valid_codes[0]);

int is_valid_code(const char* code)
{
    for (int i = 0; i < valid_codes_size; ++i)
    {
        if (strcmp(code, valid_codes[i]) == 0)
            return 1;
    }
    return 0;
}
bolov
  • 72,283
  • 15
  • 145
  • 224