思路
- 使用getchar()逐个读取字符
while((ch = getchar())!='/n')
- 使用if判断是否为数字,是的话存入字符串数组中
- 将字符数组转为整型数组,使用
atoi
代码
头文件
点击查看代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void timu_21();
func.c
点击查看代码
#include "func.h"
//该部分参考:https://blog.csdn.net/linuxlinuxlinuxlinux/article/details/9621673
void timu_21(int* year, int* month, int* date, int* hour, int* minute, int* second)
{
int dayOfMonth[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if (*year < 0 || *month < 1 || *month > 12 ||
*date < 1 || *date > 31 || *hour < 0 || *hour > 23 ||
*minute < 0 || *minute > 59 || *second < 0 || *second >60)
return;
if (*year % 400 == 0 || *year % 100 != 0 && *year % 4 == 0)
dayOfMonth[1] = 29;
++(*second);
if (*second >= 60)
{
*second = 0;
*minute += 1;
if (*minute >= 60)
{
*minute = 0;
*hour += 1;
if (*hour >= 24)
{
*hour = 0;
*date += 1;
if (*date > dayOfMonth[*month - 1])
{
*date = 1;
*month += 1;
if (*month > 12)
{
*month = 1; *year += 1;
}
}
}
}
}
return;
}
main.c
点击查看代码
#include "func.h"
int main() {
//一共需要六个元素 year, month, date, hour, minute, second;
char ch;
char time[12][4] = { 0 }; //存储中文字符会多用一行
int element_time[6] = { 0 }; //转存为整型数组,一共六个元素
int i = 0; //行数
int j = 0; //列数
int n = 0; //时间元素个数
printf("请输入时间:");
while ((ch = getchar()) != '\n') { //逐个读取字符
if (ch <= '9' && ch >= '0') { //读到字符后就放入字符数组中
time[i][j] = ch;
j++;
}
else {
j = 0;
i++;
}
}
//字符数组转换为整型
char time_t[10] = { 0 }; //一行一行转换
i = 0;
while(i<12) {
for (j = 0; j < 4; j++) {
time_t[j] = time[i][j];
}
element_time[n] = atoi(time_t);
n++;
i = i+2; //可以看看字符数组,会发现数字在数组中是隔一行存储的
}
/*for (n = 0; n < 6; n++) {
printf("%d ", element_time[n]);
}*/ //用来检测整数型数组
timu_21(&element_time[0], &element_time[1], &element_time[2], &element_time[3], &element_time[4], &element_time[5] );
printf("\n%d年%d月%d日%d时%d分%d秒。\n", element_time[0], element_time[1], element_time[2], element_time[3], element_time[4], element_time[5]);
}