c - 即使我在 C 程序中给出不同的输入,也能获得相同的输出

标签 c string memory time

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

而且我的字符串部分打印,而不是在第一个 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[]) 函数中。请记住,在您的程序中,i 是一个static 全局变量。因此,当 long EpochValue(char a[]) 函数的 while 循环中前三次调用 void toInt(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/

相关文章:

C++ 返回 float

c++ - 如何在 C++ 中读取/写入应用程序的内存

c - 编译器是否在创建目标代码之前生成隐式转换的代码?

c - 未初始化的结构 c

java - 手动实现 String.length 方法

string - VB6 相当于 string.IsNullOrEmpty

java - 为什么我会收到此错误 'illegal start of type' ?

c - 在 C 中写入并关闭文件后读取文件

c - aio_write 和 memset 参数无效和段错误(核心已转储)

c - 解释值驻留在 Linux 32 位进程地址空间中的位置