Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. strtod
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. double parse_double(const char *str) {
  7. char *tmp = 0;
  8. double result = 0;
  9.  
  10. asprintf(&tmp, "%.3s", str);
  11. result = strtod(tmp, 0);
  12. free(tmp);
  13.  
  14. return result;
  15. }
  16.  
  17. int main(void) {
  18. printf("%fn", parse_double("1.23")); // 1.2
  19. printf("%fn", parse_double("1234")); // 123
  20. printf("%fn", parse_double("0.09")); // 0.0
  21.  
  22. return 0;
  23. }
  24.  
  25. #include <stdio.h>
  26.  
  27. double parseDouble(const char *str){
  28. double val = 0;
  29. int numCharsRead;
  30.  
  31. // Handle errors by setting or returning an error flag.
  32. if(sscanf(str, "%3lf%n", &val, &numCharsRead) != 1){
  33. puts("Failed to parse double!");
  34. }
  35. else if(numCharsRead != 3){
  36. puts("Read less than three characters!");
  37. }
  38.  
  39. return val;
  40. }
  41.  
  42. int main(){
  43. printf("%lfn", parseDouble("1.3")); // 1.300000
  44. printf("%lfn", parseDouble("1.5999")); // 1.500000
  45. printf("%lfn", parseDouble(".391")); // 0.390000
  46. printf("%lfn", parseDouble(".3")); // Read less than three characters!n0.300000
  47. return 0;
  48. }
  49.  
  50. double strtod(const char *nptr, char **endptr);
  51.  
  52. /*
  53. * Same as strtod() but only takes the first n characters into account.
  54. * Additionally returns 0. and sets errno to EINVAL if 'nptr' is NULL.
  55. */
  56. double strntod(const char *nptr, char **endptr, size_t n)
  57. {
  58. double result;
  59.  
  60. /* perform input validation */
  61. if (!nptr)
  62. {
  63. errno = EINVAL;
  64.  
  65. result = 0.;
  66. if (endptr)
  67. {
  68. *endptr = nptr;
  69. }
  70.  
  71. goto lblExit;
  72. }
  73.  
  74. if (strlen(nptr) <= n)
  75. {
  76. /* Nothing to truncate: fall back to standard 'strtod()' */
  77. result = strtod(nptr, endptr);
  78. }
  79. else
  80. {
  81. /* create working copy of string */
  82. char * ptmp = strdup(nptr);
  83.  
  84. /* Test whether 'strdup()' failed */
  85. if (!ptmp)
  86. {
  87. result = 0.;
  88. if (endptr)
  89. {
  90. *endptr = nptr;
  91. }
  92.  
  93. goto lblExit;
  94. }
  95.  
  96. /* truncate working copy to n characters */
  97. ptmp[n] = '';
  98.  
  99. /* do original 'strtod()' on truncated working copy */
  100. result = strtod(ptmp, endptr);
  101.  
  102. /* adjust '*endptr' to point to original character array, but to working copy */
  103. if (endptr)
  104. {
  105. *endptr = nptr + (*endptr - ptmp);
  106. }
  107.  
  108. /* free working copy */
  109. free(ptmp);
  110. }
  111.  
  112. lblExit:
  113.  
  114. return result;
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement