C++ 流 iomanip 相当于 sprintf "%5.3f"

C++ stream iomanip equivalent to sprintf "%5.3f"

我正在尝试将 sprintf 语句转换为 C++ 流语句。 我要复制的 sprintf 格式化语句是“%5.3f”

我正在使用命名空间 std 并包含

我有:

double my_double = GetMyDoubleFromSomewhere();

stringstream ss;

ss << ??? << my_double;

我一直在查看 fixed 和 setprecision,但不太明白如何设置原始格式说明符的 5 和 3?

您想使用 io 操纵器 std::setwstd::setprecision,例如:

ss << std::setw(5) << std::setprecision(3) << my_double;

setprecisionsetw 会帮助你。 不要忘记包括 iomanip

#include <iostream>
#include <iomanip>
#include <stdio.h>

int main(void) {
  using namespace std;
  double target = 1.2345;

  cout << fixed << setw(5) << setprecision(3) << target << endl;;
  printf("%5.3f\n", target);
}