C language - format specifier preceded by modifier

        In C language, some modifiers can be added in front of the format specifier to control the format of the output or input, mainly including width, precision, left-justification flag and prefix padding character, etc.

 1. Width


        %[width]type: width here is a non-negative integer, indicating the minimum width of the output field. If the actual number of data digits is less than the specified width, spaces or 0s (depending on the padding characters) will be added on the left to reach the specified width.

printf("%10d", 5);

//将输出“      5”,其中“5”前面有7个空格。


 2. Precision


        %.precision[type]: For floating point numbers, .precision specifies the number of digits after the decimal point; for strings, it represents the maximum number of characters output, and will be truncated if exceeded.

printf("%.2f", 3.14159);

//将输出“3.14”。


 3. Left-justification mark (Left-justification)


         - is used to indicate left alignment, that is, when the width requirements are met, the data is displayed on the left, and the insufficient part is filled with padding characters on the right side.

printf("%-10d", 5);

//将输出“5      ”,其中“5”后面有7个空格。


 4. Prefix Padding Character


 • By default, spaces are used as padding characters when padding is required. Padding with 0s can be specified by inserting 0 between the width and the sign.

printf("%010d", 5);

//将输出“0000000005”,左侧用0填充至10位。

5. * In the format string of printf or scanf series functions, it can indeed be used to obtain the width or precision value from the parameter list.

        Specifically, the % in the format string is followed by an asterisk * and another number. This asterisk does not directly specify the width or precision, but indicates that the actual value should be obtained from the corresponding parameter list.

 1. 宽度:

宽度由参数动态决定

int width = 10;
printf("%*d", width, some_integer_value); // 这里宽度(field width)由变量width提供

上述代码将打印出一个整数,其左对齐且至少占据10个字符宽度,不足部分用空格填充。

 2. 精度:

对于浮点数或者字符串(%s)也有类似的情况,但通常用于浮点数的精度控制:

int precision = 3;
float value = 3.14159265;
printf("%.3f", value); // 静态指定小数点后3位精度
printf("%.*f", precision, value); // 动态指定小数点后的精度由变量precision提供

在第二个 printf 调用中,.* 表示浮点数的精度由 precision 变量提供的值来确定。

通过这种方式,在运行时根据需要调整输出格式的宽度或精度,而无需硬编码到格式化字符串中。

 

Guess you like

Origin blog.csdn.net/W_Fe5/article/details/135337477