Hi,
how to check the given string is numeric or not , without converting ( using strtol...).
for ex: if string is C01 - non-numeric data
if string is 001 - numeric data
TIA
Hi,
how to check the given string is numeric or not , without converting ( using strtol...).
for ex: if string is C01 - non-numeric data
if string is 001 - numeric data
TIA
You are trying with following standard C library function:
This function test only for decimal-digit character
http://www.freebsd.org/cgi/man.cgi?query=isdigit&sektion=3&apropos=0&manpath=FreeBSD\+6.2-RELEASE
This function test for hexadecimal-digit character
http://www.freebsd.org/cgi/man.cgi?query=isxdigit&apropos=0&sektion=0&manpath=FreeBSD\+6.2-RELEASE&format=html
Best regards,
Iliyan Varshilov
i don't want to check in a loop using isdigit. need something simple.
You are trying to solve your validation problem with regular expression library function .
http://www.opengroup.org/onlinepubs/000095399/functions/regcomp.html
Best regards,
Iliyan Varshilov
You are posting is a C programming forum and loops are too difficult?
You could make your own function:
#include <stdlib.h>
short strchk (char *s) {
unsigned short r = 0;
while (*++s) {
if (isdigit(s)) {
r = 1;
} else {
r = 0;
break;
}
}
return r;
}
Note that I didn't compile this code, but it should work.
That routine does not check the first character of the string...
Try
int is_numeric(const char *p) {
if (*p) {
char c;
while ((c=*p++)) {
if (!isdigit(c)) return 0;
}
return 1;
}
return 0;
}
Then you need to use a higher level language. C works at a low level - meaning you develop yourself a library of stuff like: a my_isnumeric() function.
Most C programmers have dozens of little functions they keep around just for stuff like this.
Thanks for correcting my code.
I'm actually using that function in a project right now, I'm making my own version of a Reverse Polish Nation calculator. But I made one modification:
if (!isdigit(c) && c != '.') return 0;
Now it has support for floating point and double.
I just wrote a script that needed to see if a value was numeric. After reading the above thread, I discovered a simpler way: exploit 'test':
The working code is embedded in a Makefile:
STATUS := $(shell echo `test $${PICTOOLSDEBUG:-0} -gt 0` $$?)
ifeq ($(STATUS),0)
else ifeq ($(STATUS),1)
else
$(error PICTOOLSDEBUG is ${PICTOOLSDEBUG}, \
but should be a small non-negative integer)
endif
More succinctly as a sh script this would be
test $Var -gt 0
if [ $? -ge 2 ] ; then ...is not numeric...; else .. is numeric; fi
Fred Hansen
Assuming you have the string in a variable A ,
echo $A | egrep "[1]+$"
if [ $? -eq 0 ]
then
echo "$A is numeric"
else
echo "$A is not numeric"
fi
IF clause can be modified to suit your requiremnent !! Hope this helps.
0-9 ↩︎
A bad way to check this is to use expr
If VAL is the value you want to check ...
[ "X`expr $VAL + 0 2>/dev/null`" != "X" ] || echo "$VAL is not numeric"