Is There A Way To Check If argv[1] Is An Integer?

Bill Poser poser at csli.Stanford.EDU
Sat Dec 23 12:41:54 AEST 1989


	tps at chem.ucsd.edu (Tom Stockfisch) suggests the following in
place of my regexp based solution:

	int	/* really BOOL */
	isInteger(string)
		char	*string;
	{	
		char	*endptr;
	
		(void)strtol( string, &endptr, 10 );
		return	endptr != string;
	}

and goes on to suggest that the regexp solution involves unnecessary
software.

	One reason not to use this version is because it doesn't
work. Since strtol sets endptr to point to the character that terminated
the scan, it returns true if a non-null prefix of the string is an integer,
which is not the same thing as testing whether the string as a whole
is an integer. To use strtol to do this correctly you have to check
whether endptr is the same as the end of the string.

	Now, if you aren't loading the regexp stuff for any other
purpose, you can keep your code size down a bit by avoiding the use
of regexp. But if you're using regexp anyhow (your interactive program
does have apropos, doesn't it?) it doesn't cost much to use it here.

	The other reason to use the regexp approach is that it makes
it quite simple to implement other predicates. Want to see if the
string is a positive integer? Just get rid of the - in the regular
expression. Want to see if you've got a floating point number in
non-exponential notation? Want to see if you've got a specified number
of digits? These are all easy to do using regular expressions, but
harder to do otherwise. Regular expression techniques provide very
general and flexible solutions to problems of this class. If you really
have a situation in which the overhead is a problem, by all means
use more specialized techniques with lower overhead, but just as it is
foolish to engage in speed optimizations that have little real impact
on performance, so it is foolish to avoid simple general techniques
when it isn't clear that the overhead is significant.

							Bill



More information about the Comp.lang.c mailing list