在c中为字符串添加零填充?
这个概念与此非常相似,但这是c#提出的问题,而不是c 虽然您可以像这样在printf中添加零填充在c中为字符串添加零填充?,c,C,这个概念与此非常相似,但这是c#提出的问题,而不是c 虽然您可以像这样在printf中添加零填充printf(“%4d”,number) 如何对字符串进行零填充?例: char *file_frame = "shots"; strcat(file_frame, "%3d", number); // It's my attempt to solve it. I know it's wrong 这样我就可以从文件(u frame)中获取shots000,您需要使用sprintf sprintf(f
printf(“%4d”,number)
如何对字符串进行零填充?例:
char *file_frame = "shots";
strcat(file_frame, "%3d", number); // It's my attempt to solve it. I know it's wrong
这样我就可以从
文件(u frame)
中获取shots000
,您需要使用sprintf
sprintf(file_frame, "%04d", 34);
0
表示填充的内容,4
显示整数的长度
您还应该使用可变数组,如下所示
char *file_frame = "shots"; --> char file_frame[100] = "shots";
首先,您需要一些空间来存储字符串。然后将“打印”到该字符串中:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char file_name[8 + 1]; // "shots###" is 8 characters, plus 1 for end-of-string marker '\0'
int number = 23;
sprintf(file_name, "shots%03d", number);
printf("\"%s\"\n", file_name);
return EXIT_SUCCESS;
}
#包括
#包括
内部主(空){
char file_name[8+1];/“shots#####”是8个字符,加上1表示字符串结束标记“\0”
整数=23;
sprintf(文件名,“快照%03d”,编号);
printf(“\%s\”\n”,文件名);
返回退出成功;
}
您可以在任何*printf()
函数中组合文字部分和格式部分