Originally Posted by
towed
My question is: is their a way to know or test to see if str will be a int or a float?
Many ints will also be floats. I would choose to use strtol and strtof to attempt conversion of the text. If either is successful, you know what you got. If neither is successful, odds are it was neither. The order of calling these two allows you to have preference for one or the other. Something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
union uType
{
int i;
float f;
};
struct tType
{
enum eType
{
TYPE_INT, TYPE_FLOAT, TYPE_OTHER, TYPE_TOTAL
} type;
union uType value;
};
int foo(struct tType *data, const char *text)
{
char *end;
data->value.i = strtol(text, &end, 10);
if ( end > text && *end == '\0' )
{
data->type = TYPE_INT;
return 1;
}
data->value.f = strtof(text, &end);
if ( end > text && *end == '\0' )
{
data->type = TYPE_FLOAT;
return 1;
}
data->type = TYPE_OTHER;
return 0;
}
int main()
{
const char *input[] =
{
"",
"-123",
"-123.45",
"123E-2",
"123abc",
"xyz",
"123E2",
"1.23.E2",
};
size_t i;
for ( i = 0; i < sizeof input / sizeof *input; ++i )
{
struct tType data;
int result = foo(&data, input[i]);
printf("\"%s\" : ", input[i]);
switch ( data.type )
{
case TYPE_INT: printf("TYPE_INT %d", data.value.i); break;
case TYPE_FLOAT: printf("TYPE_FLOAT %g", data.value.f); break;
default: fputs("TYPE_OTHER", stdout); break;
}
putchar('\n');
}
return 0;
}
/* my output
"" : TYPE_OTHER
"-123" : TYPE_INT -123
"-123.45" : TYPE_FLOAT -123.45
"123E-2" : TYPE_FLOAT 1.23
"123abc" : TYPE_OTHER
"xyz" : TYPE_OTHER
"123E2" : TYPE_FLOAT 12300
"1.23.E2" : TYPE_OTHER
*/