Skip to main content
3 of 3
edited tags
200_success
  • 145.6k
  • 22
  • 191
  • 481

Checking if each char in a string is a decimal digit

I had to write a program that would verify that a string contains any digits beside numbers 0-9 and the first '-' sign to indicate if pos/neg. The algorithm works like I want it to, but is there a better way of writing it, e.g. streamlining it, making it shorter?

bool isNum(string number) {
    // Checks if first char in buffer contains invalid digits 
    // Needed because any negative sign after the one used to indicate negative sign.
    if (!((number[0] >= '0' && number[0] <= '9') || number[0] == '-' || number[0] == '+'))
        return false;
    
    // Checks if each digit after the first is anything but 0-9
    for (int i = 1; number[i] != '\0'; i++) {
        if (number[i] < '0' || number[i] > '9')
            return false;
    }
    // If neither statement returns false, returns true by default
    return true;
}
rchkrvr2
  • 181
  • 1
  • 1
  • 3