将整数转换为C中的特定格式化字符串(HH:MM:SS)

时间:2017-09-21 11:01:07

标签: c time

我正在尝试创建一个基本警报,其中用户输入开始时间(HHMMSS)和结束时间(HHMMSS),我希望以格式(HH:MM:SS)显示此时间(24小时时间) )。我目前在这,但我遇到了分段错误。我对Coding中的Coding相当新,所以非常感谢任何帮助。

int main() { 
    int present_time; 
    int time_for_alarm; 
    char outputHolder[30]; 
    printf ("Please input present time\n"); 
    scanf ("%d", &present_time); 
    printf ("Please input time for alarm\n"); 
    scanf ("%d", &time_for_alarm); 
    strftime(present_time, sizeof(present_time), "%H:%M:%S", outputHolder); 
    while (present_time < time_for_alarm) { 
        sleep(1); 
        printf ("%d\n", present_time); 
        present_time++; 
    } 
    sleep(1); 
    printf ("ALARM"); 
    return (0); 
}

3 个答案:

答案 0 :(得分:0)

添加必要的包括:

#include <stdio.h>
#include <time.h>
#include <unistd.h>

将错误消息简化为

gcc-7 -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds      46342229.c    -o 46342229
46342229.c: In function ‘main’:
46342229.c:13:14: warning: passing argument 1 of ‘strftime’ makes pointer from integer without a cast [-Wint-conversion]
     strftime(present_time, sizeof(present_time), "%H:%M:%S", outputHolder);
              ^~~~~~~~~~~~
In file included from 46342229.c:2:0:
/usr/include/time.h:205:15: note: expected ‘char * restrict’ but argument is of type ‘int’
 extern size_t strftime (char *__restrict __s, size_t __maxsize,
               ^~~~~~~~
46342229.c:13:62: warning: passing argument 4 of ‘strftime’ from incompatible pointer type [-Wincompatible-pointer-types]
     strftime(present_time, sizeof(present_time), "%H:%M:%S", outputHolder);
                                                              ^~~~~~~~~~~~
In file included from 46342229.c:2:0:
/usr/include/time.h:205:15: note: expected ‘const struct tm * restrict’ but argument is of type ‘char *’
 extern size_t strftime (char *__restrict __s, size_t __maxsize,
               ^~~~~~~~

由此可以很容易地看出,您的strftime()调用的参数错误排序 - 您可能需要strftime(outputHolder, sizeof outputHolder, "%H:%M:%S", &alarm_tm);之类的内容,其中alarm_tm是适当的填充{ {1}}。

答案 1 :(得分:0)

我只想添加一些关于strftime()的使用情况。

它的原型是

size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)

最后一个参数必须是struct tm的地址。

创建struct tm指针并阅读其tm_hourtm_mintm_sec元素。

time_t t;
time(&t);
struct tm *ptr=localtime(&t);
printf ("Please input present time\n"); 
scanf ("%2d%2d%2d", &ptr->tm_hour, &ptr->tm_min, &ptr->tm_sec); 

然后使用strftime()

strftime(outputHolder, sizeof(outputHolder), "%H:%M:%S", ptr);

答案 2 :(得分:-1)

您没有以正确的方式使用strftime。

阅读以下两个内容,他们会解释并说明如何正确使用C语言中的时间和stftime。

  1. How to print time in format: 2009‐08‐10 18:17:54.811
  2. http://man7.org/linux/man-pages/man3/strftime.3.html