Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A few issues ...
- //
- // 1. Use of `pow` here isn't warranted -- it adds slowness and imprecision.
- //
- // 2. `search_first_character_in_text` could be replaced by `strchr`. It is
- // called twice. But, could be eliminated.
- //
- // 3. `char_to_digit` should return `int`. It could also be simplified.
- // But it could/should be eliminated.
- //
- // 4. The `template` has `typename number` but `number` isn't used.
- //
- // 5. Not really a good candidate for a `template`
- //
- // 6. No error checking
- //
- // 7. No real need to pass the string length. A running check for EOS (0x00)
- // is sufficient (faster).
- //
- // Unfortunately, I had to completely restructure your code.
- #include <stdio.h>
- #include <stdlib.h>
- double
- text_to_number(const char *text,int *erroff)
- {
- const char *cur = text++;
- int chr;
- int neg = 0;
- int gotdot = 0;
- int fractional_div = 1.0;
- double converted_number = 0.0;
- // NOTE: replace the error handling with whatever you'd like (e.g. throw)
- *erroff = -1;
- // assume number is (of the form):
- // -34531.742
- // handle negative sign
- chr = *cur;
- if (chr == '-') {
- neg = 1;
- ++cur;
- }
- for (chr = *cur++; chr != 0; chr = *cur++) {
- // look for the "."
- if (chr == '.') {
- // we got: 123.45.6
- if (gotdot) {
- *erroff = cur - text;
- break;
- }
- gotdot = 1;
- continue;
- }
- // valid digit
- if ((chr >= '0') && (chr <= '9')) {
- // get the value
- double dig = chr - '0';
- // convert fractional part:
- // 7 --> 0.7
- // 4 --> 0.04
- // 2 --> 0.002
- if (gotdot) {
- fractional_div *= 10.0;
- dig /= fractional_div;
- }
- // convert main part
- else
- converted_number *= 10.0;
- // add in the digit
- converted_number += dig;
- continue;
- }
- // invalid syntax
- *erroff = cur - text;
- break;
- }
- // apply sign
- if (neg)
- converted_number = -converted_number;
- return converted_number;
- }
- void
- test(const char *text)
- {
- int erroff;
- double ret = text_to_number(text,&erroff);
- printf("'%s' --> %.15g",text,ret);
- if (erroff >= 0) {
- text += erroff;
- printf(" ERROR: '%s'",text);
- }
- printf("\n");
- }
- int
- main(void)
- {
- test("34531.742");
- test("-34531.742");
- test("-34531.7426821");
- test("-345.31.7426821");
- test("-34531.7426-821");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment