日期和纪元值未更新。即使多次给出不同的输入,我也会得到相同的输出。谁能告诉我解决方案吗?

而且我的字符串是部分打印的,而不是在第一个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

最佳答案

问题出在void toInt(char a[])函数中。请记住,程序中的istatic全局变量。因此,在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++;
    }

}


这解决了您的问题:)

关于c - 即使我在C程序中提供了不同的输入,也将获得相同的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43670319/

10-09 23:02