Floating point format for std::ostream(std::ostream 的浮点格式)
问题描述
如何使用 std::cout 执行以下操作?
How do I do the following with std::cout?
double my_double = 42.0;
char str[12];
printf_s("%11.6lf", my_double); // Prints " 42.000000"
我正准备放弃并使用 sprintf_s.
I am just about ready to give up and use sprintf_s.
更一般地说,我在哪里可以找到关于 std::ostream 格式的参考,它在一个地方列出所有内容,而不是在长篇教程中将它们全部展开?
More generally, where can I find a reference on std::ostream formatting that lists everything in one place, rather than spreading it all out in a long tutorial?
编辑 2017 年 12 月 21 日 - 请参阅下面的答案.它使用了我在 2012 年问这个问题时不可用的功能.
EDIT Dec 21, 2017 - See my answer below. It uses features that were not available when I asked this question in 2012.
推荐答案
std::cout << std::fixed << std::setw( 11 ) << std::setprecision( 6 ) << my_double;
你需要添加
#include <iomanip>
您需要流操纵器
你可以用你想要的任何字符填充"空白的地方.像这样:
You may "fill" the empty places with whatever char you want. Like this:
std::cout << std::fixed << std::setw( 11 ) << std::setprecision( 6 )
<< std::setfill( '0' ) << my_double;
这篇关于std::ostream 的浮点格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::ostream 的浮点格式


基础教程推荐
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17