简体   繁体   English

C 程序:memcpy 正在复制奇怪的数据

[英]C program: memcpy is copying weird data

C program: The memcpy function seems to be copying the wrong data. C 程序:memcpy 函数似乎复制了错误的数据。 The purpose is to take a date parameter of character data (EX: "2019-01-06-20.03.29.004217") and convert it to YYYYMMDD format as an integer.目的是取一个字符数据的日期参数(EX:“2019-01-06-20.03.29.004217”),将其作为整数转换为YYYYMMDD格式。 My goal is to read only the numbers for year, month, and day when storing them as a string.我的目标是在将它们存储为字符串时仅读取年、月和日的数字。 Then, concatenate all into a single string.然后,将所有内容连接成一个字符串。 Finally, I want to convert the YYYYMMDD string to an integer and return it.最后,我想将 YYYYMMDD 字符串转换为整数并返回。

When executed, I only see the year being returned.执行时,我只看到返回的年份。 Is it something that C isn't recognizing?这是 C 无法识别的东西吗? I'm lost as to why this is happening.我不知道为什么会这样。 Please assist.请协助。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int getNumDate2 (char *dte);
    

int main()
{
    char prodDate[26 + 1];
    strcpy(prodDate,"2019-01-06-20.03.29.004217");// original date of character data

       printf("%d", getNumDate2(prodDate));

    return 0;
}

int getNumDate2(char *dte)
{
  static char orig_date[26 + 1];
  static char new_date[8 + 1];
  static char year[4 + 1];
  static char mth[2 + 1];
  static char day[2 + 1];
  int new_date_num;

  
  strcpy(orig_date, dte);//store original characters from date
  memcpy(year, orig_date, sizeof(year));//copy year
  memcpy(mth, orig_date+5, sizeof(mth));//copy month  
  memcpy(day, orig_date+8, sizeof(day));//copy year
  
  strcat(new_date, year);//concat date
  strcat(new_date, mth);
  strcat(new_date, day);
  sscanf(new_date,"%d", &new_date_num);//convert string YYYYMMDD to integer YYYYMMDD
  
  return new_date_num;  
}

Why not use some of what scanf can do:为什么不使用scanf可以做的一些事情:

int getNumDate2(char *dte) {
    int year, month, day;
    sscanf(dte, "%d-%d-%d", &year, &month, &day);
    return (year*100+month)*100+day;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM