c语言输入五组时间比较时间先后
时间: 2023-08-02 14:33:43 浏览: 142
实这个功能需要用到结构体和指针。下面是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_TIME_STR_LEN 20
typedef struct Time {
int year;
int month;
int day;
int hour;
int minute;
int second;
} Time;
void get_time_str(char *str, const Time *time) {
sprintf(str, "%04d-%02d-%02d %02d:%02d:%02d", time->year, time->month, time->day, time->hour, time->minute, time->second);
}
int main() {
char time_str[MAX_TIME_STR_LEN];
Time times[5];
printf("Please enter five times (format: YYYY-MM-DD HH:MM:SS):\n");
for (int i = 0; i < 5; i++) {
printf("Time %d: ", i + 1);
if (fgets(time_str, MAX_TIME_STR_LEN, stdin) == NULL) {
printf("Failed to read input.\n");
return 1;
}
time_str[strlen(time_str) - 1] = '\0'; // Remove the trailing newline character
struct tm tm_time = {0};
if (strptime(time_str, "%Y-%m-%d %H:%M:%S", &tm_time) == NULL) {
printf("Invalid time format.\n");
return 1;
}
times[i].year = tm_time.tm_year + 1900;
times[i].month = tm_time.tm_mon + 1;
times[i].day = tm_time.tm_mday;
times[i].hour = tm_time.tm_hour;
times[i].minute = tm_time.tm_min;
times[i].second = tm_time.tm_sec;
}
// Sort the array of times in ascending order
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
time_t t1 = mktime(&((struct tm){0, times[i].minute, times[i].hour, times[i].day, times[i].month - 1, times[i].year - 1900, 0, 0, -1}));
time_t t2 = mktime(&((struct tm){0, times[j].minute, times[j].hour, times[j].day, times[j].month - 1, times[j].year - 1900, 0, 0, -1}));
if (t1 > t2) {
Time tmp = times[i];
times[i] = times[j];
times[j] = tmp;
}
}
}
printf("The times in ascending order:\n");
for (int i = 0; i < 5; i++) {
get_time_str(time_str, ×[i]);
printf("%s\n", time_str);
}
return 0;
}
```
运行结果如下:
```
Please enter five times (format: YYYY-MM-DD HH:MM:SS):
Time 1: 2022-01-01 12:00:00
Time 2: 2021-12-31 18:00:00
Time 3: 2022-01-02 09:30:00
Time 4: 2022-01-03 00:00:00
Time 5: 2021-12-31 23:59:59
The times in ascending order:
2021-12-31 18:00:00
2021-12-31 23:59:59
2022-01-01 12:00:00
2022-01-02 09:30:00
2022-01-03 00:00:00
```
在示例代码中,首先定义了一个结构体Time用来存储年月日时分秒,然后通过get_time_str()函数将时间转换为字符串格式便于输出。在主函数中,使用fgets()函数从标准输入中读取五个时间字符串,然后使用strptime()函数将字符串转换为tm结构体,再将tm结构体中的元素分别赋值给Time结构体中的元素。接着使用mktime()函数将Time结构体转换为time_t类型的时间戳,最后使用冒泡排序将五个时间按照时间先后顺序排列,并输出排序结果。
阅读全文