[libcxx-commits] [PATCH] D78816: Fix ostream for complex numbers with fixed field width

Antonio Sanchez via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Fri Apr 24 09:43:47 PDT 2020


cantonios created this revision.
cantonios added reviewers: ldionne, mclow.lists, EricWF, nick.
Herald added subscribers: libcxx-commits, dexonsmith.
Herald added a project: libc++.
Herald added a reviewer: libc++.

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

For example,

  const std::complex<float> x(10, 34);
  std::cout << std::setfill('_') << std::setw(10) << x << std::endl;

should output

  ___(10,34)

for a total width of 10, but currently does:

  _________(10,34)

for a total width of width-1+7 = 16.

This diff restores the correct behavior.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D78816

Files:
  libcxx/include/complex


Index: libcxx/include/complex
===================================================================
--- libcxx/include/complex
+++ libcxx/include/complex
@@ -244,6 +244,7 @@
 #include <stdexcept>
 #include <cmath>
 #include <iosfwd>
+#include <sstream>
 #include <version>

 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -1441,7 +1442,12 @@
 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


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D78816.259907.patch
Type: text/x-patch
Size: 790 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20200424/7efd1803/attachment-0001.bin>


More information about the libcxx-commits mailing list