Re: test if a string is a valid 'number'?
On Wed, 30 May 2007 08:21:02 -0700, WJ <WJ@discussions.microsoft.com>
wrote:
Hi,
I have a string that I want convert to a number. Before doing that, I need
to test if the string represents a valid 'number'.
I remember there is a function to do that, but I can't find it.
There are functions to determine if a character is a digit, but not to
determine if a string is a number, at least not without also converting it.
If you really wanted a separate function to perform a validity test, you
could write a regular expression for your number pattern and use it with a
regexp engine, such as CAtlRegExp. If that's not possible, it should be
simple enough to hand-translate it into a state machine.
(I am NOT using .net, I am using MFC)
Thanks.
For info on converting a string and checking it for errors with a single
function, see these messages:
http://groups.google.com/group/microsoft.public.vc.mfc/msg/298e6b7793112350
http://groups.google.com/group/microsoft.public.vc.mfc/msg/5e343eb13567cb09
The first message shows how to use strtol as an error-checking atoi, but if
you don't need to perform range verification, it's simple to modify it. The
second message talks about sign issues when using the unsigned strtox
functions. For floating point, see this message:
http://groups.google.com/group/microsoft.public.vc.mfc/msg/76f24e6d75d82f77
For CStrings, use the TCHAR versions, i.e. _tcstol et.al.
--
Doug Harrison
Visual C++ MVP