# Untitled

a guest
Jul 20th, 2014
927
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1.
2. #define white_space(c) ((c) == ' ' || (c) == '\t')
3. #define valid_digit(c) ((c) >= '0' && (c) <= '9')
4.
5. template<typename T>
6. bool naive(T & r, const char *p) {
7.
8. // Skip leading white space, if any.
9. while (white_space(*p) ) {
10. p += 1;
11. }
12.
13. r = 0.0;
14. int c = 0; // counter to check how many numbers we got!
15.
16. // Get the sign!
17. bool neg = false;
18. if (*p == '-') {
19. neg = true;
20. ++p;
21. }else if(*p == '+'){
22. neg = false;
23. ++p;
24. }
25.
26. // Get the digits before decimal point
27. while (valid_digit(*p)) {
28. r = (r*10.0) + (*p - '0');
29. ++p; ++c;
30. }
31.
32. // Get the digits after decimal point
33. if (*p == '.') {
34. T f = 0.0;
35. T scale = 1.0;
36. ++p;
37. while (*p >= '0' && *p <= '9') {
38. f = (f*10.0) + (*p - '0');
39. ++p;
40. scale*=10.0;
41. ++c;
42. }
43. r += f / scale;
44. }
45.
46. // FIRST CHECK:
47. if(c==0){return false;} // we got no dezimal places! this cannot be any number!
48.
49.
50. // Get the digits after the "e"/"E" (exponenet)
51. if (*p == 'e' || *p == 'E'){
52. unsigned int e = 0;
53.
54. bool negE = false;
55. ++p;
56. if (*p == '-') {
57. negE = true;
58. ++p;
59. }else if(*p == '+'){
60. negE = false;
61. ++p;
62. }
63. // Get exponent
64. c = 0;
65. while (valid_digit(*p)) {
66. e = (e*10) + (*p - '0');
67. ++p; ++c;
68. }
69. if( !neg && e>std::numeric_limits<T>::max_exponent10 ){
70. e = std::numeric_limits<T>::max_exponent10;
71. }else if(e < std::numeric_limits<T>::min_exponent10 ){
72. e = std::numeric_limits<T>::max_exponent10;
73. }
74. // SECOND CHECK:
75. if(c==0){return false;} // we got no exponent! this was not intended!!
76.
77. T scaleE = 1.0;
78. // Calculate scaling factor.
79.
80. while (e >= 50) { scaleE *= 1E50; e -= 50; }
81. //while (e >= 8) { scaleE *= 1E8; e -= 8; }
82. while (e > 0) { scaleE *= 10.0; e -= 1; }
83.
84. if (negE){
85. r /= scaleE;
86. }else{
87. r *= scaleE;
88. }
89. }
90.
91. // POST CHECK:
92. // skip post whitespaces
93. while( white_space(*p) ){
94. ++p;
95. }
96. if(*p != '\0'){return false;} // if next character is not the terminating character
97.
98. // Apply sign to number
99. if(neg){ r = -r;}
100.
101. return true;
102. }
RAW Paste Data