Commit 1b66d1d8 authored by Uwe Schulzweida's avatar Uwe Schulzweida
Browse files

Added parse_literal.c.

parent 5fc7ce6f
&_global_ missval = -1.e33 /
&topo
att-name-dashes = 4
att.name.dots = 5
att+name+plusses = 6
att@name@ats = 7
att_byte = 0b, 127b, -128b, -1b
att_short = -32768s, 0s, 32767s
att_int = -2147483647, 0, 2147483647
att_float = -1.e+36f, 0.f, 1.e+36f
att_double = -1.e+308, 0., 1.e+308
att_char_empty = ""
att_char_single = "x"
att_char_string = "abcd\tZ$&"
/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
enum literal_type {E_LTYPE_NONE = 1, E_LTYPE_BYTE, E_LTYPE_SHORT, E_LTYPE_INT, E_LTYPE_FLOAT, E_LTYPE_DOUBLE};
// CHECK RANGE!!!
int literal_type(const char *literal)
{
if ( literal && *literal )
{
char *endptr;
errno = 0;
long lval = strtol(literal, &endptr, 10);
if ( errno == 0 && *endptr == 0 ) return E_LTYPE_INT;
else if ( errno == 0 && *(endptr+1) == 0 )
{
if ( *endptr == 's' && ( lval >= SHRT_MIN && lval <= SHRT_MAX) )
return E_LTYPE_SHORT;
else if ( *endptr == 'b' && ( lval >= SCHAR_MIN && lval <= SCHAR_MAX) )
return E_LTYPE_BYTE;
}
else
{
errno = 0;
float fval = strtof(literal, &endptr);
(void) fval;
if ( errno == 0 && (*endptr == 0 || (*(endptr+1) == 0 && *endptr == 'f')) )
return E_LTYPE_FLOAT;
else
{
double dval = strtod(literal, &endptr);
(void)dval;
if ( *endptr == 0 ) return E_LTYPE_DOUBLE;
}
}
}
return E_LTYPE_NONE;
}
int main(void)
{
const char *literals[] = {"127b", "-32768s", "-2147483647", "-1.e+36f", "1.e+308"};
int nliterals = sizeof(literals) / sizeof(literals[0]);
for ( int i = 0; i < nliterals; ++i )
printf("%d %s type = %d\n", i+1, literals[i], literal_type(literals[i]));
return 0;
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment