Last active
October 18, 2020 12:01
-
-
Save yves-chevallier/510490cb2f428a3e17d4f7f5b8e849e8 to your computer and use it in GitHub Desktop.
Tire Code
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
| #include <regex.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <stdbool.h> | |
| /** | |
| * Convert a regex match into an integer | |
| */ | |
| int to_integer(regmatch_t match, const char* str) { | |
| const char *end = &str[match.rm_eo]; | |
| return strtol(&str[match.rm_so], (char**)&end , 10); | |
| } | |
| struct tire { | |
| double width; | |
| double ratio; | |
| double rim; | |
| }; | |
| bool parse_tire_code(char * code, struct tire *par) | |
| { | |
| // Build regular expressions | |
| regex_t regex; | |
| const char *re = "^(P|LT|ST|T)([0-9]{3})/([0-9]{2,3})[BDR ]([0-9]{2})$"; | |
| if (regcomp(®ex, re, REG_EXTENDED) != 0) { | |
| fprintf(stderr, "Could not compile regex\n"); | |
| abort(); | |
| } | |
| // Execute regular expression | |
| const int groups = 5; | |
| regmatch_t matches[groups]; | |
| if (regexec(®ex, code, groups, matches, 0)) | |
| return 1; | |
| // Extract components | |
| const char * codi = "P225/55R15"; | |
| double width = to_integer(matches[2], codi) / 1000.0; // mm to meters | |
| double ratio = to_integer(matches[3], codi) / 100.0; // percent to ratio | |
| double rim = to_integer(matches[4], codi) * 25.4e-3; // inches to meters | |
| // Check for errors | |
| if (width == 0 || ratio == 0 || rim == 0 || ratio > 200) { | |
| return 1; | |
| } | |
| // Atomic return | |
| par->width = width; | |
| par->ratio = ratio; | |
| par->rim = rim; | |
| regfree(®ex); | |
| return 0; | |
| } | |
| int main() | |
| { | |
| struct tire par; | |
| if (parse_tire_code("P225/55R15", &par)) { | |
| exit(1); | |
| } | |
| printf("%f %f %f\n", par.width, par.ratio, par.rim); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment