Last active
March 18, 2016 13:22
-
-
Save ikrabbe/94df85203ace95542ba8 to your computer and use it in GitHub Desktop.
A parse_float function with test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum parseFloatErrorCodes { | |
SUCCESS, DOUBLE_DOT,PARSE_ERROR, INTEGER_OVERFLOW, | |
TOO_MANY_DIGITS_AFTER_DECIMAL_POINT | |
}; | |
int parse_float(char* inp, float *x) | |
{ | |
char *p; | |
int ival, dot; | |
for (ival = 0, dot = 0, p = inp; *p; ++p) { | |
int overflow_check = ival; | |
if (('0' <= *p) && (*p <= '9')) { | |
ival = ival * 10 + (int)(*p - '0'); | |
if (dot > 0) ++dot; | |
} else if (*p == '.') { | |
if (dot > 0) { return DOUBLE_DOT; } | |
dot = 1; | |
} else { return PARSE_ERROR; } | |
if (overflow_check > ival) { return INTEGER_OVERFLOW; } | |
} | |
*x = ival; | |
if (dot == 0) *x *= 100.0; | |
else if (dot == 1) *x *= 100.0; | |
else if (dot == 2) *x *= 10.0; | |
else if (dot > 3) { return TOO_MANY_DIGITS_AFTER_DECIMAL_POINT; } | |
*x /= 100.0; | |
return SUCCESS; | |
} | |
#include <stdio.h> | |
#include <string.h> | |
void print_error(const char* buf, int code) | |
{ | |
const char* str[] = { | |
"SUCCESS", "DOUBLE_DOT", | |
"PARSE_ERROR", "INTEGER_OVERFLOW", | |
"TOO_MANY_DIGITS_AFTER_DECIMAL_POINT" | |
}; | |
if((SUCCESS <= code) && (code <= TOO_MANY_DIGITS_AFTER_DECIMAL_POINT)) { | |
printf("parse of \"%s\" failed with %s\n", buf, str[code]); | |
} else { | |
printf("unkown error code %d\n", code); | |
} | |
} | |
int main(int argc, char** argv) | |
{ | |
const char *inp[] = { | |
"123", | |
"934.23", | |
"579346.24", | |
"1.5", | |
".2", | |
"3205986024967406709846.35", | |
"4535.23.13", | |
"SOMETHING ELSE", | |
"38575.23Numbers", | |
"123,54", | |
"0.123", | |
"" | |
}; | |
const char** I = inp; | |
char buf[40]; | |
int len; | |
for (; strlen(*I) > 0; ++I) { | |
float x = .0f; | |
int errcode = SUCCESS; | |
len=strlen(*I); | |
if(len > 39) { printf("buffer overflow.\n"); return -1; } | |
memcpy(buf, *I, len); | |
buf[len] = '\0'; | |
errcode = parse_float(buf, &x); | |
if (errcode == SUCCESS) { | |
printf("read float %5.2f\n", x); | |
} else { | |
print_error(buf, errcode); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More error codes triggered: