一般在处理时间的时候,界面上显示,打印输出这些场景下,左边补0或者补空格占位是很常见的。
补0或者补空格之后,长度是固定的;这样显示更加美观、不会因为数字变短、变长造成闪烁感。
示例代码:int main()
{
printf("%d\n",12345); //正常打印
printf("%10d\n",12345); //右对齐.位数不够,左边自动补空格
printf("%-10d,%c\n", 12345,'A');//左对齐.位数不够,右边自动补空格
printf("%010d\n",12345); //右对齐.位数不够,左边自动补0
//sprintf用法一样.
return 0;
}
输出结果:
12345
12345
12345 ,A
0000012345
在vs2017里使用sprintf需要在属性--C/C++---预处理器---增加(_CRT_SECURE_NO_WARNINGS)
std::string MStoString(long nMicroSecond)
{
int second = nMicroSecond / 1000;
int hours, mins, secs, minSecs;
secs = second % 60;
mins = (second / 60) % 60;
hours = second / 3600;
minSecs = nMicroSecond - (hours * 3600 + mins * 60 + secs) * 1000;
char buff[1024];
//sprintf数字补0
sprintf(buff,"%02d:%02d:%02d.%02d", hours, mins, secs, minSecs);
std::string strTime = buff;
return strTime;
}
int main()
{
printf("%s\n", MStoString(50000).c_str());
return 0;
}