test_nonfinite_loopback.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Distributed under the Boost Software License, Version 1.0.
  2. // (See accompanying file LICENSE_1_0.txt
  3. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. // Copyright (c) 2006 Johan Rade
  5. // Copyright (c) 2011 Paul A. Bristow
  6. /*!
  7. \file
  8. \brief Basic tests of native nonfinite loopback.
  9. \detail Basic loopback test outputs using the platforms built-in facets
  10. and reads back in, and checks if loopback OK.
  11. Using MSVC this doesn't work OK:
  12. input produces just "1" instead of "1.#QNAN", 1.#SNAN" or 1.#IND"!
  13. */
  14. #include <iostream>
  15. using std::cout;
  16. using std::endl;
  17. #include <locale>
  18. using std::locale;
  19. #include <string>
  20. using std::string;
  21. #include <sstream>
  22. using std::stringstream;
  23. #include <limits>
  24. using std::numeric_limits;
  25. int main()
  26. {
  27. locale default_locale; // Current global locale.
  28. // Try to use the default locale first.
  29. // On MSVC this doesn't work.
  30. { // Try infinity.
  31. stringstream ss; // Both input and output.
  32. ss.imbue(default_locale); // Redundant, of course.
  33. string infs;
  34. if(numeric_limits<double>::has_infinity)
  35. { // Make sure infinity is specialised for type double.
  36. double inf = numeric_limits<double>::infinity();
  37. ss << inf; // Output infinity.
  38. infs = ss.str(); //
  39. }
  40. else
  41. { // Need to provide a suitable string for infinity.
  42. infs = "1.#INF"; // Might suit MSVC?
  43. ss << infs;
  44. }
  45. double r;
  46. ss >> r; // Read back in.
  47. cout << "infinity output was " << infs << endl; // "1.#INF"
  48. cout << "infinity input was " << r << endl; // "1"
  49. }
  50. { // Try Quiet NaN
  51. stringstream ss; // Both input and output.
  52. ss.imbue(default_locale); // Redundant, of course.
  53. string infs;
  54. if(numeric_limits<double>::has_quiet_NaN)
  55. { // Make sure quiet NaN is specialised for type double.
  56. double qnan = numeric_limits<double>::quiet_NaN();
  57. ss << qnan; // Output quiet_NaN.
  58. infs = ss.str(); //
  59. }
  60. else
  61. { // Need to provide a suitable string for quiet_NAN.
  62. infs = "1.#QNAN";
  63. ss << infs;
  64. }
  65. double r;
  66. ss >> r; // Read back in.
  67. cout << "quiet_NaN output was " << infs << endl; // "1.#QNAN"
  68. cout << "quiet_NaN input was " << r << endl; // "1#"
  69. }
  70. } // int main()
  71. /*
  72. Output (MSVC Version 10.0):
  73. infinity output was 1.#INF
  74. infinity input was 1
  75. quiet_NaN output was 1.#QNAN
  76. quiet_NaN input was 1
  77. */