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 的浮点格式
基础教程推荐
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
