I have a string(char*), and i need to find its underlying datatype such as int, float, double, short, long, or just a character array containing alphabets with or with out digits(like varchar in SQL). For ex:
char* str1 = '12312' char* str2 = '231.342' char* str3 = '234234243234' char* str4 = '4323434.2432342' char* str5 = 'i contain only alphabets'
Given these strings, i need to find that the first string is of type int and typecast it to an int, and so on ex:
int no1 = atoi(str1) float no2 = atof(str2) long no3 = atol(str3) double no4 = strtod(str4) char* varchar1 = strdup(str5)
Clarifying a bit more…
I have a string and its contents could be alphabets and/or digits and/or special characters. Right now, I am able to parse string and
- Identify if it contains only digits,
Here i convert the string into short or int or long, based on best fit. ( How do i know if the string can be converted to an short int or long?) - Only alphabets, leave it as a string.
- Digits with a single decimal point.
Here i need to convert the string into float or double ( Same question here) - other. leave it as a string
In C (not in C++), I would use a combination of strtod/strol and max values from <limits.h> and <float.h>:
Which results in the following:
Sorry for my rusty C.
🙂
So, in substance, you after the call of whatIsTheValue, you retrieve the type through the MyEnum enum, and then, according to the value in this enum, retrieve the right value, correctly typed, from the union MyUnion.
Note that finding if the number is a double or a float is a bit more complicated because the difference seems to be in the precision, i.e. is your number representable in a double, or in float. A most ‘decimal real’ numbers are not exactly representable into a double, I would not bother.
Note, too, that there is a catch, as 25.0 could be both real and an integer number. My comparing ‘dValue == (double)(long)dValue’, I guess you should know if is an integer, again, not taking into account the usual precision problems coming witb binary real numbers used by computers.