Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(???):
}
like image 577
Crystal Avatar asked Jul 02 '26 11:07

Crystal


1 Answers

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.

like image 97
Alexander Gessler Avatar answered Jul 05 '26 17:07

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!