1

I'm trying to get some formatting done in my sprintf statement, but it doesn't seem to work as I expect. Here is the line:

n = sprintf(buffer, "x = %d.%d, y = %d.%d, z = %d.%d \n", x1, x2, y1, y2, z1, z2);

In that printout x1 is the whole part of the number, and x2 is the fractional part. All would be well, except I need to pad x2, y2, and z2 to always be 2 digits - meaning I need to pad with leading zeros.

With examples that I see online it seems like doing this should work:

n = sprintf(buffer, "x = %d.%02d, y = %d.%02d, z = %d.%02d \n", x1, x2, y1, y2, z1, z2);

However, that instead produces something like this:

x = 2.2d, y = 37.2d, z = 2.2d

The 37 above is actually x2, and it apparently got shifted over in place of y1. I tried putting brackets around the '02', but that doesn't do anything either.

I have tried splitting up the period too like this: (but that didn't work)

   n = sprintf(buffer, "x = %d. %02d, y = %d. %02d, z = %d. %02d \n", x1, x2, y1, y2, z1, z2);

I'm not really sure what's wrong... I'd appreciate any help. This isn't particularly vital to do in sprintf (I could theoretically write some 'if' statements and get it working that way), but it'd be nice.

Thanks!

4

1 回答 1

1

这是一个示例代码和输出。

float x1 = 10.12222;
float y1 = 20.23333;
float z1 = 30.34444;
int   xi = 10;
int   yi = 20;
int   zi = 30;
int   x0 = 5;
int   y0 = 5;
int   z0 = 5;
int   xl = 10;
int   yl = 10;
int   zl = 10;
char  chr[512];

printf("x = %5.2f, y = %5.2f, z = %5.2f\n", x1, y1, z1);
printf("x = %10d, y = %10d, z = %10d\n", xi, yi, zi);
printf("x = %010d, y = %010d, z = %010d\n", xi, yi, zi);
printf("x = %-10d, y = %-10d, z = %-10d\n", xi, yi, zi);
printf("x = %10.5d, y = %10.5d, z = %10.5d\n", xi, yi, zi); // DYNAMIC

/* Dynamic formatting of DYNAMIC commented line*/
sprintf(chr, "Dynamic: x = %%%d.%dd, y = %%%d.%dd, z = %%%d.%dd\n",
        xl, x0, yl, y0, zl, z0);
printf(chr, xi, yi, zi);

输出将是这样的。

x = 10.12, y = 20.23, z = 30.34
x =         10, y =         20, z =         30
x = 0000000010, y = 0000000020, z = 0000000030
x = 10        , y = 20        , z = 30
x =      00010, y =      00020, z =      00030
Dynamic: x =      00010, y =      00020, z =      00030

%x.yd 的意思是,

x - 整数的总字符数。

y - 在该长度内用 0 填充。

%10.5d 将为 10、100、1000、10000、100000、100000 给出以下结果

bbbbbbbbbb => Spaces
     00010
     00100
     01000
     10000
    100000
   1000000

我希望这对您的格式化有所帮助。

于 2013-06-20T01:31:14.247 回答