日期和纪元价值未更新。即使我给出不同的输入次数,我也得到相同的输出。有人可以告诉我解决方案吗?
我的字符串也是部分打印,而不是在第一个printf()语句中打印完整日期。我想打印它像2017-04-23。但它只打印2017年。如何打印整个日期?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void toInt(char []);
long EpochValue(char []);
int y1,m1,d1;
static int i=1;
int main()
{
long epoch;
char a[20] = "2017-04-23";
printf("epoch value of %s is %ld\n",a,EpochValue(a));
char b[20] = "2016-12-11";
printf("epoch value of %s is %ld\n",b,EpochValue(b));
char c[20] = "2014-09-08";
printf("epoch value of %s is %ld\n",c,EpochValue(c));
return 0;
}
long EpochValue(char a[])
{
int month,date,year;
struct tm *day;
time_t epoch,today;
char *token = strtok(a,"-");
while(token!=NULL){
toInt(token);
token = strtok(NULL,"-");
}
year = y1;
month = m1;
date = d1;
printf("\nyear: %d\n month %d\n day %d\n",year,month,date);
time(&today);
day = localtime(&today);
day->tm_mon = month-1;
day->tm_mday = date;
day->tm_year = year-1900;
epoch = mktime(day);
printf("u were born on %d/%d/%d\n",date,month,year);
return epoch;;
}
void toInt(char a[]) {
if(i==1)
y1 = atoi(a);
if(i==2)
m1 = atoi(a);
if(i==3)
d1 = atoi(a);
i++;
}
我每次都得到相同的输出,你可以在下面看到
year: 2017
month 4
day 23
u were born on 23/4/2017
epoch value of 2017 is 1492995157
year: 2017
month 4
day 23
u were born on 23/4/2017
epoch value of 2016 is 1492995157
year: 2017
month 4
day 23
u were born on 23/4/2017
epoch value of 2014 is 1492995157
答案 0 :(得分:1)
问题出在void toInt(char a[])
函数中。请记住,在您的计划中,i
是一个static
全局变量。因此,在void toInt(char a[])
函数的while循环中首次调用long EpochValue(char a[])
函数时。 i的值超过3.现在下次再次调用该函数时,void toInt(char a[])
函数中的所有三个条件都将为false
,因为i
将大于3。
void toInt(char a[]) { /* Conditions below are true only when function called thrice for first time, that's why you see the same first values again and again. */
if(i==1)
y1 = atoi(a);
if(i==2)
m1 = atoi(a);
if(i==3)
d1 = atoi(a);
i++;
}
尝试使用这个,我在你的函数中强加了一个新的条件来处理这个问题:
void toInt(char a[]) {
if(i==1)
y1 = atoi(a);
if(i==2)
m1 = atoi(a);
if(i==3)
d1 = atoi(a);
if(i==3) /* Making Sure that Value of i is reset after reaching three */
{
i=1;
}
else
{
i++;
}
}
这解决了你的问题:)