-3

Is it possible to check if a string variable is entirely numeric? I know you can iterate through the alphabets to check for a non-numeric character, but is there any other way?

  • 2
    Look up `strtol`. If the `endptr` points one past the last character, all characters were converted. – AbdullahC Oct 07 '13 at 00:58
  • Is this **really** a bottleneck for you? If not just use something easy. If it is you can use various SSE tricks to process more than one character in your block at a time (I've seen this done for whitespace - but don't have an example handy). You can also split your chunks up and spread across multiple threads. But really these will be overkill for most situations. – Michael Anderson Oct 07 '13 at 01:24

3 Answers3

1

The quickest way i can think of is to try to cast it with "strtol" or similar functions and see whether it can convert the entire string:

char* numberString = "100";
char* endptr;
long number = strtol(numberString, &endptr, 10);
if (*endptr) {
    // Cast failed
} else {
    // Cast succeeded
}

This topic is also discussed in this thread: How to determine if a string is a number with C++?

Hope this helps :)

Community
  • 1
  • 1
torpedro
  • 464
  • 4
  • 12
1
#include <iostream>
#include <string>
#include <locale>
#include <algorithm>

bool is_numeric(std::string str, std::locale loc = std::locale())
{
    return std::all_of(str.begin(), str.end(), std::isdigit);
}

int main()
{
    std::string str;
    std::cin >> str;

    std::cout << std::boolalpha << is_numeric(str); // true
}
0x499602D2
  • 87,005
  • 36
  • 149
  • 233
0

You can use the isdigit function in the ctype library:

  #include <stdio.h>
  #include <stdlib.h>
  #include <ctype.h>
  int main ()
  {
    char mystr[]="56203";
    int the_number;
    if (isdigit(mystr[0]))
    {
      the_number = atoi (mystr);
      printf ("The following is an integer\n",the_number);
    }
   return 0;
  }

This example checks the first character only. If you want to check the whole string then you can use a loop, or if its a fixed length and small just combine isdigit() with &&.

henderso
  • 985
  • 7
  • 13