Re: Smart conversion from a string to different type of numbers



d.avitabile@xxxxxxxxx wrote On 04/30/07 13:44,:
I have a C++ code that is reading a list of parameters from a file.

PARAMETERS stringParam="stringValue", intParam=4, doubleParam =
3.533, ... END

The values can be strings as well as integers or doubles, and I don't
know what they will be ( I don't know how the parameter list will look
like) . At the moment I have a mechanism that select all the values
and read them into C++ strings, regardless of their type.

What I need is a function that converts smartly my strings into
numbers: for instance, if I fed it with "4", it would return me the
type "integer" and store the value 4 accordingly, whereas if I fed it
with a "3.533" it would return the type "double" and store the value
3.533.

If you want a C++ solution, try a C++ newsgroup.

In C, I'd approach the problem by using a struct
and a union, something like:

struct number {
enum { ERROR, LONG, DOUBLE } type;
union {
long l;
double d;
} value;
};

.... with a function that first tries to convert the string
with strtol(), and if that doesn't work tries again with
strtod(), and gives up if neither works:

#include <stdlib.h>

struct number
getNumber(const char *string)
{
struct number n;
char *endp;

n.value.l = strtol(string, &endp, 10);
if (endp != string && *endp == '\0') {
n.type = LONG;
return n;
}

n.value.d = strtod(string, &endp);
if (endp != string && *endp == '\0') {
n.type = DOUBLE;
return n;
}

n.type = ERROR;
return n;
}

A C++ addict might take a different approach.

--
Eric.Sosman@xxxxxxx
.



Relevant Pages