[libcxx-commits] [libcxx] aa0b991 - [libc++] Fix ostream for complex numbers with fixed field width

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu May 7 10:51:19 PDT 2020


Author: Antonio Sanchez
Date: 2020-05-07T13:51:07-04:00
New Revision: aa0b991dcf0510793a42a5b01aaf06a6c0892bcf

URL: https://github.com/llvm/llvm-project/commit/aa0b991dcf0510793a42a5b01aaf06a6c0892bcf
DIFF: https://github.com/llvm/llvm-project/commit/aa0b991dcf0510793a42a5b01aaf06a6c0892bcf.diff

LOG: [libc++] Fix ostream for complex numbers with fixed field width

The ostream operator<< is currently broken for std::complex with
specified field widths.

This patch a partial revert of c3478eff7a65 (reviewed as D71214),
restoring the correct behavior.

Differential Revision: https://reviews.llvm.org/D78816

Added: 
    

Modified: 
    libcxx/include/complex
    libcxx/test/std/numerics/complex.number/complex.ops/stream_output.pass.cpp

Removed: 
    


################################################################################
diff  --git a/libcxx/include/complex b/libcxx/include/complex
index 92295be976cc..36c66db50e68 100644
--- a/libcxx/include/complex
+++ b/libcxx/include/complex
@@ -244,6 +244,7 @@ template<class T, class charT, class traits>
 #include <stdexcept>
 #include <cmath>
 #include <iosfwd>
+#include <sstream>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -1441,7 +1442,12 @@ template<class _Tp, class _CharT, class _Traits>
 basic_ostream<_CharT, _Traits>&
 operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x)
 {
-    return __os << '(' << __x.real() << ',' << __x.imag() << ')';
+    basic_ostringstream<_CharT, _Traits> __s;
+    __s.flags(__os.flags());
+    __s.imbue(__os.getloc());
+    __s.precision(__os.precision());
+    __s << '(' << __x.real() << ',' << __x.imag() << ')';
+    return __os << __s.str();
 }
 
 #if _LIBCPP_STD_VER > 11

diff  --git a/libcxx/test/std/numerics/complex.number/complex.ops/stream_output.pass.cpp b/libcxx/test/std/numerics/complex.number/complex.ops/stream_output.pass.cpp
index 9e7049ea93bd..cfdedda52e60 100644
--- a/libcxx/test/std/numerics/complex.number/complex.ops/stream_output.pass.cpp
+++ b/libcxx/test/std/numerics/complex.number/complex.ops/stream_output.pass.cpp
@@ -20,10 +20,20 @@
 
 int main(int, char**)
 {
-    std::complex<double> c(1, 2);
-    std::ostringstream os;
-    os << c;
-    assert(os.str() == "(1,2)");
+    {
+        std::complex<double> c(1, 2);
+        std::ostringstream os;
+        os << c;
+        assert(os.str() == "(1,2)");
+    }
+    {
+        std::complex<double> c(1, 2);
+        std::ostringstream os;
+        os.width(8);
+        os.fill('_');
+        os << c;
+        assert(os.str() == "___(1,2)");
+    }
 
   return 0;
 }


        


More information about the libcxx-commits mailing list