c++ - 如何从系统日期获取昨天的日期并附加到字符串?

标签 c++ c date system runtime-error

我是 C 编程的初学者,我试图通过 C 代码使用系统日期获取昨天的日期,并像这样 yesterdayDate_dtmmddyy 追加字符串“yesterdayDate_dt”,但遇到运行时错误“bus error 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 文档并尝试以下代码

#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;
}

关于c++ - 如何从系统日期获取昨天的日期并附加到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493637/

相关文章:

c - C 中 char 数组的异常初始值设定项

java智能日期解析器

c++ - 使用 BGL 创建生成树

c++ - 这一行是否声明了一个函数? C++

c++ - 将 unordered_map 元素保存到指针/迭代器

c++ - vector 比较

c - 具有动态矩阵的动态结构

调用函数(argc,argv);在C中

java - 如何在java中将时间戳转换为日期和时间?

mysql - 每分钟 SQL 插入量