首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C中的strptime解析不一致?

C中的strptime解析不一致?
EN

Stack Overflow用户
提问于 2017-02-28 13:51:27
回答 1查看 102关注 0票数 3

我在尝试使用C语言中的strptime函数时遇到了奇怪的行为。

代码语言:javascript
运行
复制
#include <stdio.h>
#define __USE_XOPEN
#define _GNU_SOURCE
#include <time.h>
#include <stdlib.h>
#include <unistd.h>


int parseTime(char *timestamp)
{

    time_t t1;
    struct tm *timeptr,tm1;
    char* time1 = timestamp;


    //(1) convert `String to tm`:  
    if(strptime(time1, "%Y/%j/%H/%M/%S",&tm1) == 0)
    {
        fprintf(stderr,"\nInvalid timestamp\nTimestamp should be in the format: YYYY/DDD/HH/MM/SS\n");
        exit(EXIT_FAILURE); 
    }         

    //(2)   convert `tm to time_t`:    
    t1 = mktime(&tm1);

    return t1;
}


int main(int argc, char const *argv[])
{
     int now = parseTime(argv[1]);  

     int wait = parseTime(argv[2]) - now;

     printf("%d\n", wait);


    return 0;
}

我以./timetest 2400/001/00/00/00 2400/001/00/00/08的形式运行这个程序

以下是一些终端输出:

代码语言:javascript
运行
复制
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

3608

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

3608

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

8

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

8

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

8

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

8

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

3608

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

3608

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

8

$ ./timetest 2400/001/00/00/00 2400/001/00/00/08

3608

有没有什么我遗漏的东西会导致这些不一致的结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-28 14:14:32

可能是在使用strptime之前未初始化tm

初始化tm:memset(&tm, 0, sizeof(struct tm));

Documentation指出,在被strptime调用之前,tm通常不会初始化。这取决于您使用的实现/UNIX系统。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42501161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档