c - 如何在 C 中用零填充空白(整数)位置?

标签 c time formatting printf string-formatting

我想在 C 整数中添加前导零。我正在做一个时钟。这是我到目前为止的代码:

int main(){

    while (1){
    time_t present;
    time(&present);
    struct tm *myTime =  localtime(&present);
    printf("%2d:%2d:%2d\n", myTime->tm_hour,myTime->tm_min, myTime->tm_sec);
    sleep(1);
    }

    return 0;
}

这是当前的输出:

11:30: 0
11:30: 1
11:30: 2
11:30: 3
11:30: 4
11:30: 5
11:30: 6
11:30: 7
11:30: 8
11:30: 9
11:30:10

这是我想要的输出:

11:30:00
11:30:01
11:30:02
//and so on...

最佳答案

% 和长度修饰符之间填充一个 0,这里是 2,在 printf() 中的每个格式说明符处调用:

printf("%02d:%02d:%02d\n", myTime->tm_hour,myTime->tm_min, myTime->tm_sec);
         |    |    |
        here here here

关于c - 如何在 C 中用零填充空白(整数)位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61301542/

相关文章:

c - 试图让 scanf 不去 for 循环中的新行(C 编程)

date - Flutter:国际时间

datetime - 如何在 Crystal Reports 中显示当前日期和时间?

用于 Linux 和/或 MonoDevelop 的 C# 代码格式化程序

c - 尝试执行 "strrev",来自整数的指针而不进行强制转换

在 Julia 基准教程中编译 C 代码

c - C 中的关联数组

ruby-on-rails - 如何从月份编号获取月份名称

Javascript 和/或 jQuery 时间码格式

ios - iPhone : How to get number from string with currency symbol in Objective-C