Discussion:
how to convert CString and std::string to number?
(too old to reply)
kathy
2005-11-10 23:36:27 UTC
Permalink
How to determine if the CString and std::string is a number and how to
convert it to number?
beginthreadex
2005-11-10 23:41:30 UTC
Permalink
int i = atoi(std::string::c_str());
Post by kathy
How to determine if the CString and std::string is a number and how to
convert it to number?
--
new
Tom Serface
2005-11-10 23:59:03 UTC
Permalink
A tricky way to do this for CString would be to use:


{
CString cs = _T("124.3");

if(bIsNumber(cs)) {
float d = _tstof(cs);
// Do other stuff
}
}

BOOL bIsNumber(const char *csStr)
{
const char *myNumber = _T("0123456789. ");
CString cs = csStr;
return(cs.Trim(myNumbers).IsEmpty()); // All numeric characters or
space
}

Tom
Post by kathy
How to determine if the CString and std::string is a number and how to
convert it to number?
beginthreadex
2005-11-11 00:09:34 UTC
Permalink
Below is a differnt method. Of course, neither of these correctly deals with
'.', '$', '-', <spaces>, <cents sign>, or exponents just to name a few.


BOOL bIsNumber(const char *csStr)
{
unsigned long testedStringLength = strlen(csStr);

for (unsigned long testingIndex = 0; testingIndex < testedStringLength;
++testingIndex)
{
if (csStr[testingIndex] < '0' || csStr[testingIndex] > '9')
return false;
}

return true;
}
Post by Tom Serface
{
CString cs = _T("124.3");
if(bIsNumber(cs)) {
float d = _tstof(cs);
// Do other stuff
}
}
BOOL bIsNumber(const char *csStr)
{
const char *myNumber = _T("0123456789. ");
CString cs = csStr;
return(cs.Trim(myNumbers).IsEmpty()); // All numeric characters or
space
}
Tom
Post by kathy
How to determine if the CString and std::string is a number and how to
convert it to number?
--
new
Doug Harrison [MVP]
2005-11-11 00:45:00 UTC
Permalink
Post by kathy
How to determine if the CString and std::string is a number and how to
convert it to number?
See these messages:

http://groups-beta.google.com/group/microsoft.public.vc.mfc/msg/298e6b7793112350
http://groups-beta.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
--
Doug Harrison
Visual C++ MVP
Josh McFarlane
2005-11-11 01:02:36 UTC
Permalink
Post by kathy
How to determine if the CString and std::string is a number and how to
convert it to number?
All the conversions you need and more:

http://msdn2.microsoft.com/en-us/library/0heszx3w.aspx

(There's multiple functions for different number types as well as
unicode / mb char types)

Josh McFarlane

Loading...