Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

printf - C formatted string - How to add leading zeros to string value using sprintf?

I want to add zeroes at the starting of a string. I am using format specifier. My input string is hello I want output as 000hello.

I know how to do this for integer.

int main()
{
    int i=232;
    char str[21];
    sprintf(str,"%08d",i);

    printf("%s",str);

    return 0;
}

OUTPUT will be -- 00000232

If I do the same for string.

 int main()
    {
        char i[]="hello";
        char str[21];
        sprintf(str,"%08s",i);

        printf("%s",str);

        return 0;
    }

OUTPUT will be - hello (with 3 leading space)

Why it is giving space in case of string and zero in case of integer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to add leading zeros to string value using sprintf?

Use "%0*d%s" to prepend zeros.

"%0*d" --> 0 min width of zeros, * derived width from the argument list, d print an int.

An exception is needed when the string needs no zeros up front.

void PrependZeros(char *dest, const char *src, unsigned width) {
  size_t len = strlen(src);
  if (len >= width) strcpy(dest, src);
  else sprintf(dest, "%0*d%s", (int) (width - len), 0, src);
}

Yet I do not think sprintf() is the right tool for the job and would code as below.

// prepend "0" as needed resulting in a string of _minimal_ width.
void PrependZeros(char *dest, const char *src, unsigned minimal_width) {
  size_t len = strlen(src);
  size_t zeros = (len > minimal_width) ? 0 : minimal_width - len;
  memset(dest, '0', zeros);
  strcpy(dest + zeros, src);
}

void testw(const char *src, unsigned width) {
  char dest[100];
  PrependZeros(dest, src, width);
  printf("%u <%s>
", width, dest);
}

int main() {
  for (unsigned w = 0; w < 10; w++)
    testw("Hello", w);
  for (unsigned w = 0; w < 2; w++)
    testw("", w);
}

Output

0 <Hello>
1 <Hello>
2 <Hello>
3 <Hello>
4 <Hello>
5 <Hello>
6 <0Hello>
7 <00Hello>
8 <000Hello>
9 <0000Hello>
0 <>
1 <0>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...