C++ 用 sprintf 填充

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6116994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:31:11  来源:igfitidea点击:

padding with sprintf

c++cstringprintf

提问by Abruzzo Forte e Gentile

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 sprintfformat. I am trying the following

我有一个假问题。我想用 0 将整数打印到缓冲区填充中,但我无法对sprintf格式进行排序。我正在尝试以下

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?

我究竟做错了什么?这并不意味着用 0 填充最大宽度为 30 个字符?

回答by Seth Robertson

"%030d"is the droid you are looking for

"%030d"是你要找的机器人吗

回答by Sreerac

You got the syntax slightly wrong; The following code produces the desired output:

你的语法有点错误;以下代码产生所需的输出:

char buf[31];
int my_val = 324;
sprintf( buf, "%030d", (int)my_val );

From Wikipedia's Article on Printf:

来自维基百科关于 Printf 的文章

[...] printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".

回答by Nick Meyer

The padding and width come beforethe type specifier:

填充和宽度类型说明符之前

sprintf( buf, "%030d", my_val );

回答by Matthew

Try:

尝试:

sprintf( buf, "%030d", my_val );

回答by jbruni

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'.

您的精度和宽度参数需要在 '%' 和转换说明符 'd' 之间,而不是在后面。事实上,所有的标志都可以。因此,如果您想要前面的 '+' 表示正数,请使用 '%+d'。

回答by John

It's %030d, with type-letter at the end.

它是%030d,末尾带有打字机。

回答by Lundin

A fairly effective version that doesn't need any slow library calls:

一个不需要任何缓慢库调用的相当有效的版本:

#include <stdio.h>

void uint_tostr (unsigned int n, size_t buf_size, char dst[buf_size])
{
  const size_t str_size = buf_size-1;

  for(size_t i=0; i<str_size; i++)
  {
    size_t index = str_size - i - 1;
    dst[index] = n%10 + '0';
    n/=10;
  }
  dst[str_size] = '##代码##';
}


int main (void)
{
  unsigned int n = 1234;
  char str[6+1];
  uint_tostr(n, 6+1, str);
  puts(str);
}

This can be optimized further, though it is still probably some hundred times faster than sprintfas is.

这可以进一步优化,尽管它仍然可能比sprintf现在快一百倍。