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?
Asked
Active
Viewed 147 times
-3
-
2Look 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 Answers
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 :)
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
}

David G
- 94,763
- 41
- 167
- 253
-
Why not use `std::isdigit(c, loc)`? I think it's clearer and less typing. – Blastfurnace Oct 07 '13 at 01:31
-
@Blastfurnace Is `isdigit` a C function? I'm trying to keep this entirely C++ oriented. – David G Oct 07 '13 at 01:32
-
There is a C++ `std::locale` version. See: [std::isdigit](http://en.cppreference.com/w/cpp/locale/isdigit) – Blastfurnace Oct 07 '13 at 01:34
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
- 1,035
- 8
- 13