右对齐C中填充零的字符串

时间:2013-08-13 09:15:52

标签: c string string-formatting

我想在左侧填充零填充字符串值。我写了下面的代码,但它打印的是空格而不是0。

#include<stdio.h>

    int main()
    {
            char s[4]="PJ";
            printf("%04s",s);
    }

    Output: "  PJ"

    I need output as "00PJ".

4 个答案:

答案 0 :(得分:2)

您可以这样做:

#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,则代码会更正,并且字符串后面的堆栈不会损坏。

答案 1 :(得分:0)

欣赏上述更简单的解决方案,同时提供更多手动替代方案:

#include<stdio.h>
#include<string.h>

void print(char *s, int ncount)
{
    if(s == NULL) return;
    int len = strlen(s);
    if(len > ncount) printf("%s", s);
    else {
        for(int i = 0; i < ncount - len; ++i)
            printf("0");
        printf("%s", s);
    }
}
int main()
{

    char s[4]="PJ";
    print(s, 4);
    return 0;
}

答案 2 :(得分:0)

以下是我的问题的短线代码答案: - 这将处理任何长度的输入变量,如s = "J", s="JH", s="JHA", s="PJHA" 相应的输出为"000J", "00JH", "0JHA", "PJHA"

#include<stdio.h>
#include<string.h>
int main()
{
        char s[4],s2[4];
        strcpy(s,"JH");
        sprintf(s2,"%04s",s);
        memset(s2,'0',4-(int)strlen(s));
        printf("Output =%s\n",s2);

}
Output =00JH

答案 3 :(得分:0)

#include <stdio.h>
#include <string.h>

int main(){
    char s[5]="PJ";
    char padding[sizeof(s)] = {0};
    int width = sizeof(padding)-1;

    memset(padding, '0', width);
    width -= strlen(s);

    //printf("%.*s%s\n", (int)(4-strlen(s)), "0000", s);
    printf("%.*s%s\n", width, padding, s);
    return 0;
}
相关问题