Pages

Tuesday, November 10, 2009

String to double

Probably, the C++ standard library is unlimited. There are so many functions I've never heard about. For example, only today I found out that there is strtod function:

C: strtod in stdlib.h
C++: strtod in cstdlib

I knew about atof.

But this function does not work with the strings like "20nn". So, for example, how to check if this conatins a valid double?

I made even a function and tested it in this code:
#include <cstdio>
#include <string>

bool is_valid_double(const char* str)
{
while (str && *str && *str == ' ')
str++;

if (*str && *str == '-')
str++;

while (str && *str)
{
if (!isdigit(*str) && (*str != '.'))
{
if (*str == ' ')
{
while (str && *str && *str == ' ')
str++;
if (!*str)
return true;
}
return false;
}
str++;
}

return true;
}

int main()
{
char sz[16] = { 0 };
sprintf(sz, "%f", 20.0);
bool b = is_valid_double(sz);

strcpy(sz, " 20.00");
b = is_valid_double(sz);

strcpy(sz, " 20.00 ");
b = is_valid_double(sz);

strcpy(sz, " -20.00 ");
b = is_valid_double(sz);

strcpy(sz, " --20.00");
b = is_valid_double(sz);

strcpy(sz, " 20.00 2");
b = is_valid_double(sz);

strcpy(sz, " 20nn ");
b = is_valid_double(sz);

return 0;
}
And then I see (thanks to EE), that there are a set of functions such as strtod, strtof, etc. Actually, I knew about strtol, so I could guess that should be also strtod. But I didn't. :)

No comments:

Post a Comment