fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. class Double
  8. {
  9. public:
  10. Double(const char * s);
  11.  
  12. operator double() const { return sign*v*pow(10,ex*exsn); }
  13. private:
  14.  
  15. int start(char c);
  16. int zero (char c);
  17. int one (char c);
  18. int two (char c);
  19. int three(char c);
  20. int four (char c);
  21. int five (char c);
  22.  
  23. double v = 0;
  24. int sign = 1;
  25. int ex = 0;
  26. int exsn = 1;
  27. int state = -1;
  28. double p = 10;
  29. };
  30.  
  31. Double::Double(const char * s)
  32. {
  33. if ((state = start(*s++)) < 0) return;
  34. for(;*s;++s)
  35. {
  36. switch(state)
  37. {
  38. case 0: state = zero (*s); break;
  39. case 1: state = one (*s); break;
  40. case 2: state = two (*s); break;
  41. case 3: state = three(*s); break;
  42. case 4: state = four (*s); break;
  43. case 5: state = five (*s); break;
  44. default: return;
  45. }
  46. }
  47. }
  48.  
  49. int Double::start(char c)
  50. {
  51. if (c == '-' || c == '+') { sign = (c == '-') ? -1 : 1; return 0; }
  52. if (c == '.') return 2;
  53. if (isdigit(c)) { v = v*10 + (c-'0'); return 1; }
  54. return -1;
  55. }
  56.  
  57. int Double::zero(char c)
  58. {
  59. if (c == '.') return 2;
  60. if (isdigit(c)) { v = v*10 + (c-'0'); return 1; }
  61. return -1;
  62. }
  63.  
  64. int Double::one(char c)
  65. {
  66. if (c == '.') return 2;
  67. if (c == 'e' || c == 'E') return 4;
  68. if (isdigit(c)) { v = v*10 + (c-'0'); return 1; }
  69. return -1;
  70. }
  71.  
  72. int Double::two(char c)
  73. {
  74. if (isdigit(c)) { v = v + (c-'0')/p; p*=10; return 3; }
  75. return -1;
  76. }
  77.  
  78. int Double::three(char c)
  79. {
  80. if (isdigit(c)) { v = v + (c-'0')/p; p*=10; return 3; }
  81. if (c == 'e' || c == 'E') return 4;
  82. return -1;
  83. }
  84.  
  85. int Double::four(char c)
  86. {
  87. if (c == '-' || c == '+') { exsn = (c == '-') ? -1 : 1; return 5; }
  88. if (isdigit(c)) { ex = ex*10 + (c-'0'); return 5; }
  89. return -1;
  90. }
  91.  
  92. int Double::five(char c)
  93. {
  94. if (isdigit(c)) { ex = ex*10 + (c-'0'); return 5; }
  95. return -1;
  96. }
  97.  
  98. int main(int argc, char * argv[])
  99. {
  100. string s;
  101. while(cin >> s)
  102. {
  103. cout << setw(15) << s << " " << setprecision(25) << Double(s.c_str()) << endl;
  104. }
  105. }
  106.  
Success #stdin #stdout 0.01s 5528KB
stdin
3.14151926
0.256E18
-.123e45
1.2a763527
+.456tt7862
stdout
     3.14151926  3.141519260000000368648898
       0.256E18  256000000000000000
       -.123e45  -1.23000000000000001342895e+44
     1.2a763527  1.199999999999999955591079
    +.456tt7862  0.4560000000000000164313008