【问题标题】:How to get yesterday's date from system date and append to string?如何从系统日期获取昨天的日期并附加到字符串?
【发布时间】:2013-01-24 03:50:14
【问题描述】:

我是 C 编程的初学者,我尝试使用系统日期通过 c 代码获取昨天的日期,并像这样昨天Date_dtmmddyy 附加到字符串“yesterdayDate_dt”中,但遇到运行时错误“总线错误 10”。

我的代码如下

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
 
int main(void)
{
   time_t now = time(NULL);
   struct tm *t = localtime(&now);
 
  int dInt = t->tm_mday+1;
  int mInt = t->tm_mon -1;
  int yInt = t->tm_year+1900;
  char *date= "23";
  char *month = "01";
  char *year = "13";
 
  sprintf(date, "%d", dInt);
  sprintf(month, "%d", mInt);
 
   char *yestDt = (char *)malloc(strlen(date)+strlen(month)+strlen(year)+1);
   strcpy(str,month);
   strcat(str,date);
   strcat(str,year);
   printf("str:%s",yestDt);
   return 0;
}

【问题讨论】:

  • 再次查看sprintf的一些文档。

标签: c++ c date system runtime-error


【解决方案1】:

请查看 sprintf 文档并尝试以下代码

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
 
int main(void)
{
    char yestDt[23];
    time_t now = time(NULL);
    now = now - (24*60*60);
    struct tm *t = localtime(&now);
    sprintf(yestDt,"yesterdayDate_dt%02d%02d%02d", t->tm_mon+1, t->tm_mday, t->tm_year - 100);
    printf("Target String: \"%s\"", yestDt);
    return 0;
}

【讨论】:

    【解决方案2】:

    此代码不合法​​:

    sprintf(date, "%d", dInt);
    

    sprintf 期望第一个参数指向可写 字符存储。 date 未指向可写存储。

    尝试将date 的声明更改为可写字符数组:

    char date[3];
    

    【讨论】:

    • 字符日期[3]?真的吗? 3个字节的存储空间?然后使用没有字节数限制的 sprintf ?注意到任何可能的问题或缓冲区溢出问题吗?
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多