我想右对齐字符串值,并在左侧填充零。我编写了以下代码,但它打印空格而不是 0。
#include<stdio.h>
int main()
{
char s[4]="PJ";
printf("%04s",s);
}
Output: " PJ"
I need output as "00PJ".
最佳答案
你可以这样做:
#define MIN_LEN 4
if (strlen(s) < MIN_LEN) {
printf("%0*d%s", MIN_LEN-(int)strlen(s), 0, s);
}
else {
printf("%s", s);
}
不要忘记包含 <string.h>
编辑: 为了解释我们关于缓冲区溢出的讨论,只需尝试这段代码:
int main()
{
struct
{
char s[4];
int i;
} test;
test.i = 0x12345678;
strcpy(test.s,"PJHA");
printf("Output =%s\nTest =%x",test.s,test.i);
}
输出:
Output =PJHA
Test =12345600
如果将大小更改为 5
,代码将得到纠正,并且字符串后面的堆栈不会损坏。
关于c - C 中的右对齐零填充字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18205095/