x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 334

# validate a number?

Hello all

I need a function that can tell if a number is, in fact, a number.
isdigit() does it for one char, but what about, ie, 25?

The function needs to be vanilla standard STL C++.

Thanks

Edmund
0
vlg
• 3
1 Solution

Commented:
Do isdigit(char[0]).

Example:

0

Commented:
If you want to check the full string for digits, you can use the following function.

bool IsStringDigit(const char* Src)
{
int len = strlen(Src);
if (!len) return false;
for(int x = 0;x < len;++x)
{
if (!isdigit(Src[x])) return false;
}
return true;
}
0

Commented:
You could also use wht the CRT offers - the 'strtoXX()' functions have a built-in check for number formats, so if you are dealing with ints, e.g.

#include <stdlib.h>

int n;
char* psz = "253";
char* stop;

n = (int) strtol ( psz, &stop, 10);

if ( *stop) {

// if *stop is non-null, an invalid char was encountered
}

0

Author Commented:
0

Commented:
FYI:
You still have to check for he string length using the strtol method.

For example, with out checking for strlen, the following code would incorrectly interpret psz_bad2 as a number.

int n;
char* psz = "123";
char* stop;

n = (int) strtol ( psz, &stop, 10);
if (!stop[0]) printf("Is a number\n");
else printf("Not a number (%s)\n", stop);

n = (int) strtol ( psz_bad, &stop, 10);
if (!stop[0]) printf("Is a number\n");
else printf("Not a number (%s)\n", stop);

n = (int) strtol ( psz_bad2, &stop, 10);
if (!stop[0]) printf("Is a number\n");
else printf("Not a number (%s)\n", stop);

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.