数字前面加 0

发布于 2024-10-01 04:15:15 字数 896 浏览 0 评论 0原文

可能的重复:
使用 C++ 输出运算符(相当于 printf)打印前导零?

#include <iostream>
#include <iomanip>
int main()
{
   int n = 16;
   std::cout << ???(5) << n << std::endl;
}

我希望输出为 00016
setw() 前面加上空格。是否可以配置在 setw() 前面添加哪些字符?

我的最终目标是在 4 个位置打印一个十六进制 2 字节数字。像这样的东西:

#include <iostream>
#include <iomanip>
int main()
{
    unsigned short n = 0xA7;
    std::cout << std::hex << ???(4) << n << std::endl;
}

我期望得到这个输出:00A7

Possible Duplicate:
Print leading zeros with C++ output operator (printf equivalent)?

#include <iostream>
#include <iomanip>
int main()
{
   int n = 16;
   std::cout << ???(5) << n << std::endl;
}

I want the output to be 00016
setw() prepends with spaces. Isn't it configurable what characters to prepend with setw()?

My eventual goal is to print a hex 2-byte number in 4 positions. Something like this:

#include <iostream>
#include <iomanip>
int main()
{
    unsigned short n = 0xA7;
    std::cout << std::hex << ???(4) << n << std::endl;
}

and I am expecting to get this output: 00A7

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百变从容 2024-10-08 04:15:15

您还需要 setfill('0')

You also need setfill('0').

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文