fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <iomanip>
  5. #include <limits>
  6. using namespace std;
  7.  
  8. int main() {
  9. const float x = 10.0000095;
  10. const float y = 10.0000105;
  11.  
  12. // Default precision
  13. {
  14. stringstream def_prec;
  15.  
  16. // Write to string
  17. def_prec << x <<" "<<y;
  18.  
  19. // What was written ?
  20. cout <<def_prec.str()<<endl;
  21.  
  22. // Read back
  23. float x2, y2;
  24. def_prec>>x2 >>y2;
  25.  
  26. // Check
  27. printf("%.8f vs %.8f\n", x, x2);
  28. printf("%.8f vs %.8f\n", y, y2);
  29. }
  30.  
  31. cout<<endl;
  32.  
  33. // Using max_digits10
  34. const int digits_max = numeric_limits<float>::max_digits10;
  35. {
  36. stringstream max_prec;
  37. max_prec << setprecision(digits_max) << x <<" "<<y;
  38. // What was written ?
  39. cout <<max_prec.str()<<endl;
  40.  
  41. // Read back
  42. float x2, y2;
  43. max_prec>>x2 >>y2;
  44.  
  45. // Check
  46. printf("%.8f vs %.8f\n", x, x2);
  47. printf("%.8f vs %.8f\n", y, y2);
  48. }
  49.  
  50. cout<<endl;
  51.  
  52. {
  53. stringstream some_prec;
  54. some_prec << setprecision(digits_max-1) << x <<" "<<y;
  55. // What was written ?
  56. cout <<some_prec.str()<<endl;
  57.  
  58. // Read back
  59. float x2, y2;
  60. some_prec>>x2 >>y2;
  61.  
  62. // Check
  63. printf("%.8f vs %.8f\n", x, x2);
  64. printf("%.8f vs %.8f\n", y, y2);
  65. }
  66.  
  67. }
Success #stdin #stdout 0s 5424KB
stdin
Standard input is empty
stdout
10 10
10.00000954 vs 10.00000000
10.00001049 vs 10.00000000

10.0000095 10.0000105
10.00000954 vs 10.00000954
10.00001049 vs 10.00001049

10.00001 10.00001
10.00000954 vs 10.00000954
10.00001049 vs 10.00000954