gpt4 book ai didi

c - c 中用 0 右填充字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:48 25 4
gpt4 key购买 nike

我在c中使用了零左填充,下面是实现代码。

unsigned char* LeftPadZero(unsigned char fa[], int flen)
{

unsigned char *fout;
int sz;
sz = snprintf(NULL,0,"%s",fa);
fout = (unsigned char*)malloc(flen+sz+1);
if(flen > 0)
{
sprintf((char*)fout,"%0*d%s", flen , 0, fa);
}
else if(flen == 0)
{
fout = fa;
}
else
{
printf("Length of number is negative\n");
return NULL;
}

return fout;

}

现在我正在尝试对右零填充做同样的事情。但不是用 0 填充。长度正在打印。例如:string000 这样它应该打印。在我的例子中它打印为 string3

unsigned char* RightPadZero(unsigned char fa[], int flen)
{

unsigned char *fout;
int sz;
sz = snprintf(NULL,0,"%s",fa);
fout = (unsigned char*)malloc(flen+sz+1);
if(flen > 0)
{
sprintf((char*)fout,"%s%0*d", fa , 0, flen);
}
else if(flen == 0)
{
fout = fa;
}
else
{
printf("Length of number is negative\n");
return NULL;
}

return fout;

}

最佳答案

长度参数必须在数据参数之前,所以试试这个

sprintf((char*)fout,"%s%0*d", fa , flen, 0);

代替

sprintf((char*)fout,"%s%0*d", fa , 0, flen);

引自 N1570 7.21.6.1 fprintf 函数,第 5 段:

As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted.

关于c - c 中用 0 右填充字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38989549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com