'Checking for numbers in a switch statement

Is there an easy way to check for digits 0-9 with a switch statement? I'm writing a program to check for certain characters as well as digits. Like checking for '\0', 'F' or 'f', and was wondering if there was also a way to check for 0-9 in a similar fashion. I know I can write a program to return true or false if a character is a digit 0-9, but wasn't sure how to use that with one of the cases in a switch statement. Like if I had:

const int lowerBound = 48;
const int upperBound = 57;

bool isDigit(char *digit)
{
    if (*digit >= lowerBound && *digit <= upperBound) {
        return true;
    }
    else {
        return false;
    }
}

how I can go

switch (*singleChar) {
    case(???):
}


Solution 1:[1]

switch(mychar) {

   case '0':
   case '1':
   case '2':
   ..
   // your code to handle them here
   break; 

   .. other cases
}

This is called 'fall-through' - if a case block does not terminate with a break, control flow continues at the next case statement.

Solution 2:[2]

Hang on! Why are you defining your own isDigit function when there's one already available in the function in the 'ctype.h' header file...Consider this:

char *s = "01234"; char *p = s;
while(*p){
    switch(*p){
        case 'A' :
            break;
        default:
            if (isdigit(*p)){
                puts("Digit");
                p++;
            }
            break;
    }
}

Solution 3:[3]

This would probably do it, but to be honest, it's pretty ugly. I'd probably use a different construct (maybe a regex?) unless I knew this was a major hotspot, and even then I'd profile.

switch (*singlChar) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
        // do stuff
        break;
    default:
        // do other stuff
}

Solution 4:[4]

I think GCC supports a non-standard extension where you can do things like this:

switch(myChar)
{
case '0'...'2':
    // Your code to handle them here
    break;

.. other cases
}

But it is NON-STANDARD and will not compile under Visual Studio for example.

Solution 5:[5]

You could do this

char input = 'a';

switch (input)
{
  case 'a': // do something; break;
  // so on and so forth...
  default: break
}

Solution 6:[6]

Please use below code.

switch (*singleChar) {

         case 48 ... 57: return true;

         default: return false; 

}

Solution 7:[7]

How about:

int isdigit(char input) {
    return (input < '0' || input > '9') ? 0 : 1; 
}

...

if(isdigit(currentChar)) {
    ...
}
else {
    switch(currentChar) {
        case 'a' {
            ...
            break;
        }
        ...
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Gessler
Solution 2
Solution 3 Hank Gay
Solution 4 Cthutu
Solution 5 Vino
Solution 6 Raj
Solution 7