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

Jos*_*itt 1 c++ stringstream

我试图将sprintf语句转换为C++流语句.我试图复制的sprintf格式化语句是"%5.3f"

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

我有:

double my_double = GetMyDoubleFromSomewhere();

stringstream ss;

ss << ??? << my_double;
Run Code Online (Sandbox Code Playgroud)

我一直在看固定和setprecision,但不能完全弄清楚如何设置原始格式说明符的5和3?

Hir*_*aki 5

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);
}
Run Code Online (Sandbox Code Playgroud)