用 sprintf 填充
我有一个虚拟问题。我想将一个整数打印到缓冲区中填充 0,但我无法将其整理为 sprintf 格式。 我正在尝试以下
char buf[31];
int my_val = 324;
sprintf( buf, "%d030", my_val );
希望有以下字符串
"000000000000000000000000000324"
我做错了什么?这并不意味着用 0 填充最大宽度为 30 个字符?
I have a dummy question. I would like to print an integer into a buffer padding with 0 but I cannot sort it out the sprintf
format.
I am trying the following
char buf[31];
int my_val = 324;
sprintf( buf, "%d030", my_val );
hoping to have the following string
"000000000000000000000000000324"
what am I doing wrong? It doesn't mean pad with 0 for a max width of 30 chars?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
“%030d”
是您要找的机器人"%030d"
is the droid you are looking for你的语法有点错误;以下代码产生所需的输出:
来自 Wikipedia 关于 Printf 的文章:
You got the syntax slightly wrong; The following code produces the desired output:
From Wikipedia's Article on Printf:
填充和宽度位于类型说明符之前:
The padding and width come before the type specifier:
尝试:
Try:
您的精度和宽度参数需要位于“%”和转换说明符“d”之间,而不是之后。事实上所有标志都是如此。因此,如果您想要前面的“+”表示正数,请使用“%+d”。
Your precision and width parameters need to go between the '%' and the conversion specifier 'd', not after. In fact all flags do. So if you want a preceeding '+' for positive numbers, use '%+d'.
它是
%030d
,末尾带有类型字母。It's
%030d
, with type-letter at the end.一个相当有效的版本,不需要任何缓慢的库调用:
这可以进一步优化,尽管它仍然可能比
sprintf
快数百倍。A fairly effective version that doesn't need any slow library calls:
This can be optimized further, though it is still probably some hundred times faster than
sprintf
as is.